How can I pass a parameter to the callback of a jQuery ajax request?
I need to pass extra variables to a jQuery, ajax callback function.
For example, given:
while (K--)
{
$.get
(
"BaseURL" + K,
function (zData, K) {ProcessData (zData, K); }
);
}
function Pr开发者_开发知识库ocessData (zData, K)
{
console.log (K);
}
ProcessData()
will report 0 every time (or whatever the last value of K was).
How do I ensure that ProcessData()
fires with, or can get, the correct value of K?
Is there any way to do this without wrapping the $get()
in a function?
No. Because of the ways closures work, all the inner functions will close over the same K variable (which ends up equalling 0). You need an additional level of indirection somewhere to create separate scopes. E.g.:
while (K--)
{
(function(K)
{
$.get
(
"BaseURL" + K,
function (zData, status) {ProcessData (zData, K); }
);
})(K);
}
Also, the second parameter of the success function shouldn't be called K. That parameter will get the status, which would then shadow the desired K.
精彩评论