是否有一种方法可以在jQuery中传递更多的数据到回调函数?

我有两个函数,我想回调到$。例如,使用post来传递AJAX调用的结果数据和一些自定义参数

function clicked() {
    var myDiv = $("#my-div");
    // ERROR: Says data not defined
    $.post("someurl.php",someData,doSomething(data, myDiv),"json"); 
    // ERROR: Would pass in myDiv as curData (wrong)
    $.post("someurl.php",someData,doSomething(data, myDiv),"json"); 
}

function doSomething(curData, curDiv) {

}

我希望能够将自己的参数传递给回调,以及从AJAX调用返回的结果。


当前回答

实际上,这比大家说的要简单得多……特别是当你使用$.ajax({})基本语法和一个helper函数时。

只要传入key: value对,就像你对任何对象一样,当你设置你的ajax请求…(因为$(this)还没有改变上下文,它仍然是上面bind调用的触发器)

<script type="text/javascript">
$(".qty input").bind("keypress change", function() {
    $.ajax({
        url: "/order_items/change/"+$(this).attr("data-order-item-id")+"/qty:"+$(this).val()+"/returnas.json",
        type: "POST",
        dataType: "json",
        qty_input: $(this),
        anything_else_i_want_to_pass_in: "foo",
        success: function(json_data, textStatus, jqXHR) {
            /* here is the input, which triggered this AJAX request */
            console.log(this.qty_input);
            /* here is any other parameter you set when initializing the ajax method */
            console.log(this.anything_else_i_want_to_pass_in);
        }
    });
});
</script>

这比设置var更好的一个原因是,var是全局的,因此,是可重写的…如果有两个东西可以触发ajax调用,理论上可以比ajax调用响应更快地触发它们,并且可以将第二个调用的值传递给第一个调用。使用上面的这个方法,就不会发生这种情况(而且使用起来也很简单)。

其他回答

实际上,这比大家说的要简单得多……特别是当你使用$.ajax({})基本语法和一个helper函数时。

只要传入key: value对,就像你对任何对象一样,当你设置你的ajax请求…(因为$(this)还没有改变上下文,它仍然是上面bind调用的触发器)

<script type="text/javascript">
$(".qty input").bind("keypress change", function() {
    $.ajax({
        url: "/order_items/change/"+$(this).attr("data-order-item-id")+"/qty:"+$(this).val()+"/returnas.json",
        type: "POST",
        dataType: "json",
        qty_input: $(this),
        anything_else_i_want_to_pass_in: "foo",
        success: function(json_data, textStatus, jqXHR) {
            /* here is the input, which triggered this AJAX request */
            console.log(this.qty_input);
            /* here is any other parameter you set when initializing the ajax method */
            console.log(this.anything_else_i_want_to_pass_in);
        }
    });
});
</script>

这比设置var更好的一个原因是,var是全局的,因此,是可重写的…如果有两个东西可以触发ajax调用,理论上可以比ajax调用响应更快地触发它们,并且可以将第二个调用的值传递给第一个调用。使用上面的这个方法,就不会发生这种情况(而且使用起来也很简单)。

当使用doSomething(data, myDiv)时,实际上是调用函数,而不是对它进行引用。

您可以直接传递doStomething函数,但必须确保它具有正确的签名。

如果你想让doSomething保持原样,你可以把它的调用包装在一个匿名函数中。

function clicked() {
    var myDiv = $("#my-div");
    $.post("someurl.php",someData, function(data){ 
      doSomething(data, myDiv)
    },"json"); 
}

function doSomething(curData, curDiv) {
    ...
}

在匿名函数代码中,可以使用封闭作用域中定义的变量。这就是Javascript作用域的工作方式。

$(document).on('click','[action=register]',function(){
    registerSocket(registerJSON(),registerDone,second($(this)));
});

function registerSocket(dataFn,doneFn,second){
                 $.ajax({
                       type:'POST',
                       url: "http://localhost:8080/store/public/register",
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       data:dataFn
                 }).done ([doneFn,second])
                   .fail(function(err){
                            console.log("AJAX failed: " + JSON.stringify(err, null, 2));
                        });
}

function registerDone(data){
    console.log(JSON.stringify(data));
}
function second(element){
    console.log(element);
}

次要途径:

function socketWithParam(url,dataFn,doneFn,param){
  $.ajax({
    type:'POST',
    url:url,
    contentType: "application/json; charset=utf-8",
    headers: { 'Authorization': 'Bearer '+localStorage.getItem('jwt')},
    data:dataFn
    }).done(function(data){
      doneFn(data,param);
    })
    .fail(function(err,status,xhr){
    console.log("AJAX failed: " + JSON.stringify(err, null, 2));
    });
}

$(document).on('click','[order-btn]',function(){
  socketWithParam(url,fakeDataFn(),orderDetailDone,secondParam);
});

function orderDetailDone(data,param){
  -- to do something --
}

让我们简单点!:)

$.ajax({
    url: myUrl,
    context: $this, // $this == Current $element
    success: function(data) {
        $.proxy(publicMethods.update, this)(data); // this == Current $element
    }
});

使用.ajax() jQuery API和闭包向回调函数传递附加参数的更通用的发送异步请求的解决方案:

function sendRequest(method, url, content, callback) {
    // additional data for the callback
    var request = {
        method: method,
        url: url
    };

    $.ajax({
        type: method,
        url: url,
        data: content
     }).done(function(data, status, xhr) {
        if (callback) callback(xhr.status, data, request);
     }).fail(function(xhr, status) {
        if (callback) callback(xhr.status, xhr.response, request);
     });
};