是否有一种方法可以在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调用返回的结果。


当前回答

你可以使用JavaScript的闭包:

function wrapper( var1, var2,....) // put here your variables
{
  return function( data, status)
  {
     //Handle here results of call
  }
};

当你可以这样做时:

$.post("someurl.php",data,wrapper(var1, var2, etc...),"html");

其他回答

我在上一篇帖子中犯了一个错误。这是一个如何在回调函数中传递额外参数的工作示例:

function custom_func(p1,p2) {
    $.post(AJAX_FILE_PATH,{op:'dosomething',p1:p1},
        function(data){
            return function(){
                alert(data);
                alert(p2);
            }(data,p2)
        }
    );
    return false;
}

实际上,你的代码不能工作,因为当你写:

$.post("someurl.php",someData,doSomething(data, myDiv),"json"); 

将函数调用作为第三个形参而不是函数引用。

使用.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);
     });
};

实际上,这比大家说的要简单得多……特别是当你使用$.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调用响应更快地触发它们,并且可以将第二个调用的值传递给第一个调用。使用上面的这个方法,就不会发生这种情况(而且使用起来也很简单)。

你也可以尝试以下方法:

function clicked() {

    var myDiv = $("#my-div");

    $.post("someurl.php",someData,function(data){
        doSomething(data, myDiv);
    },"json"); 
}

function doSomething(curData, curDiv) {

}