如何将变量绑定到jQuery Ajax请求?

5
这很容易理解:
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 中。我不能使用全局变量,因为每个 ajax 请求的 string 都是不同的。所以问题是,如何将 string 绑定到我的 ajax 请求中,以便我可以从 processData 中访问它?
我真的不想将 string 添加到查询中并让服务器返回它,但如果这是我唯一的选择,我别无选择。
提前感谢。
3个回答

7

可以试试这个方法:

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);
}

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


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是jQuery版本(跨浏览器)的.bind()

你可以像@Joel建议的一样添加参数(在他已删除的答案中),但参数越少越好


只是一个想法:如果“string”是在“while”内部发生变化的值,那么您如何确保将正确的“string”值传递给“processData”函数(而不是最后一个)? - Fabrizio Calderan
嗯,我想使用闭包来确保这一点是正确的方法。编辑,@F.Calderan。 - Florian Margaine

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接