jquery $ .ajax:将附加参数传递给'success'回调

Bin*_*hen 15 ajax jquery

我使用$ .ajax将数据发布到服务器.但是我想将一个额外的参数传递给'success'回调,以告诉回调函数响应所用的HTML元素的id.

有可能的?喜欢:

success_cb(data, elementid)
{
    (update the elementid with the server returned data)
}

$.ajax({
    ...
    success:success_cb(elementid)
});
Run Code Online (Sandbox Code Playgroud)

Hor*_*aan 23

有可能的.尝试类似的东西:

function success_cb(data, elementid)
{
    (update the elementid with the server returned data)
}

$.ajax({
    ...
    success:function(data){ success_cb(data, elementid); }
});
Run Code Online (Sandbox Code Playgroud)

  • 这个(在anon函数中包装回调)是一个直截了当的答案,我无法相信我没有立即想到它.:-) (3认同)

Phr*_*ogz 13

function postForElement(elementId){
  $.post('/foo',someValues,function(data){
    $(elementId).html("The server returned: "+data);
  },'json');
}
Run Code Online (Sandbox Code Playgroud)

通过在与elementId局部变量相同的范围内声明函数文字,该函数变为可以访问该局部变量的闭包.(或者有些人可能会说,当函数文字也引用未在其范围内定义的非全局变量时,它只会成为一个闭包.这只是用单词绑定.)