如何将变量绑定到jquery ajax请求?

时间:2012-05-22 16:12:59

标签: javascript jquery ajax data-binding jquery-deferred

这是不言自明的:

while (...) {
    var string='something that changes for each ajax request.';
    $.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'}).done(processData);
}
function processData(data) {
    // get string into here somehow.
}

正如您所看到的,我需要以某种方式将string变为processData。我无法创建全局变量,因为string对于每个ajax请求都不同。所以,问题是,如何将string绑定到我的ajax请求,以便我可以从processData访问它?

我真的不想将string附加到查询中并让服务器返回它,但如果这是我唯一的选择,我别无选择。

提前致谢。

3 个答案:

答案 0 :(得分:6)

尝试这样:

while (...) {

    var str = 'something that changes for each ajax request.';

    (function(_str) {
        $.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'})
         .done(function(data) {
            processData(data, _str);
         });
    }(str));
}

function processData(data, str) {
  console.log(data, str);
}

并且没有使用全局变量:)

答案 1 :(得分:2)

var string='something that changes for each ajax request.';
// Use a closure to make sure the string value is the right one.
(function() {
    // Store the "string" context
    var that = this;
    $.ajax({
        'type': 'GET',
        'dataType': 'json',
        'url': 'get_data.php'
    }).done(
        $.proxy( processData, that )
    );
}(string));

function processData( data ) {
    this.string === 'something that changes for each ajax request.' // true
}

$.proxy.bind()的jQuery版本(跨浏览器)。

您可以添加@Joel建议的参数(在他删除的答案中),但less arguments the better

答案 2 :(得分:0)

$(document).bind("ajaxSend",function(){
    $("#ajax_preloader").show();
}).bind("ajaxComplete",function(){
    $("#ajax_preloader").hide();
});