开发者

jquery $.ajax: pass additional argument to 'success' callback

开发者 https://www.devze.com 2023-01-26 00:38 出处:网络
I am using $.ajax to post data to the server. However I want to pass an additional parameter to the \'success\' callback to tel开发者_JAVA技巧l the callback function the id of the HTML element the res

I am using $.ajax to post data to the server. However I want to pass an additional parameter to the 'success' callback to tel开发者_JAVA技巧l the callback function the id of the HTML element the response is for.

It is possible? Like:

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

$.ajax({
    ...
    success:success_cb(elementid)
});


It is possible. Try something like:

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

$.ajax({
    ...
    success:function(data){ success_cb(data, elementid); }
});


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

By declaring the function literal in the same scope as the elementId local variable, the function becomes a closure that has access to that local variable. (Or some might say it only becomes a closure when the function literal also references the non-global variable that is not defined in its scope. That's just bandying with words.)

0

精彩评论

暂无评论...
验证码 换一张
取 消