jquery $.ajax: pass additional argument to 'success' callback
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.)
精彩评论