简体   繁体   中英

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 ProcessData (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. Eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM