使用$ .ajax传递变量

时间:2014-01-07 08:20:21

标签: php jquery ajax variables parameter-passing

我有两个复选框,其中包含以下值:

<label for="hotel_boutique"><input id="hotel_boutique" name="hotel_boutique" value="test" type=checkbox />test</label><br />

3

我用这样的Ajax调用得到这些值:

<script>
jQuery("input[type='checkbox']").change(function(){

if (jQuery('input#hotel_boutique').is(':checked')) {
    var hotel_boutique = jQuery("#hotel_boutique").map(function () {return this.value;}).get();
}else{
    var hotel_boutique = 'NULL';
    }
if (jQuery('input#hotel_stars').is(':checked')) {
    var hotel_stars = jQuery("#hotel_stars").map(function () {return this.value;}).get();
}else{
    var hotel_stars = 'NULL';
    }

var data = 'hotel_boutique="'+hotel_boutique+'"&hotel_stars="'+hotel_stars+'"';
jQuery.ajax({
    url: "processAjax.php",
    type: "GET",
    data: data,
    cache: false,
    beforeSend: function() {
        jQuery("#loading").show();
    },
    success: function(data, textStatus, XMLHttpRequest){
        jQuery("#content").html('');
        jQuery("#content").append(data);
        jQuery("#loading").hide();
    },
    error: function(MLHttpRequest, textStatus, errorThrown){
        alert(errorThrown);
    }

});
});
</script>

现在,当我回显服务器端(PHP)中的变量时,它会显示:

"test"

添加"的人和原因是什么?我该如何删除它们?

我已经尝试过PHP函数preg_replace和其他东西。

请你帮忙......

3 个答案:

答案 0 :(得分:5)

您可以使用对象而不是像

这样的字符串
var data = {
    hotel_boutique: hotel_boutique,
    hotel_stars: hotel_stars
};

问题是数据字符串中的",您也可以尝试

var data = 'hotel_boutique='+hotel_boutique+'&hotel_stars='+hotel_stars;

整体代码可以简化为

jQuery("input[type='checkbox']").change(function () {
    var data = {
        hotel_boutique: $('#hotel_boutique:checked').val()||'NULL',
        hotel_stars: $('#hotel_stars:checked').val()||'NULL'
    };
    jQuery.ajax({
        url: "processAjax.php",
        type: "GET",
        data: data,
        cache: false,
        beforeSend: function () {
            jQuery("#loading").show();
        },
        success: function (data, textStatus, XMLHttpRequest) {
            jQuery("#content").html(data);
            jQuery("#loading").hide();
        },
        error: function (MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
});

答案 1 :(得分:1)

你需要传递键值对:

data: {hotel_boutique: hotel_boutique,hotel_stars: hotel_stars},

在此电话会议中:

jQuery.ajax({
    data: data,      // change here
});

答案 2 :(得分:1)

它应该是:

jQuery.ajax({
    url: "processAjax.php",
    type: "GET",
    data: {
        hotel_boutique: hotel_boutique,
        hotel_stars : hotel_stars
     },
    cache: false,
    beforeSend: function() {
        jQuery("#loading").show();
    },
    success: function(data, textStatus, XMLHttpRequest){
        jQuery("#content").html('');
        jQuery("#content").append(data);
        jQuery("#loading").hide();
    },
    error: function(MLHttpRequest, textStatus, errorThrown){
        alert(errorThrown);
    }

});