最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery Ajax call in loop losing local variable reference - Stack Overflow

programmeradmin0浏览0评论

I am making several jQuery ajax calls within a loop. Each time one of the ajax calls return I need to reference a value corresponding to the original ajax call. My current code doesn't work properly, in that the value of the lskey variable has been altered by further loop iterations.

Here is the code:

for (var i = 0, len = localStorage.length; i < len; i++) {
        var lskey = localStorage.key(i);
        if (lskey.substr(0, 4) === 'form') {
            var postdata = localStorage.getItem(lskey); // Get the form data
            $.ajax({
                type: "POST",
                async: "false",
                url: "/Profile/PostForm",
                data: postdata,
                success: function (data) {
                    $('#rollinginfo').append('<br>' + data + ',key=' + lskey);
                    localStorage.removeItem(lskey); // Remove the relevant localStorage entry
                }
            , error: function (data) { $('#rollinginfo').append('<br />ERR:' + data); }
            });


        }
    } 

The problem is that lskey is being altered each time the loop executes, and therefore the success callback does not have a reference to the value of lskey that existed at the time of the call.

How do I reference the correct value of lskey for each success callback?

I am making several jQuery ajax calls within a loop. Each time one of the ajax calls return I need to reference a value corresponding to the original ajax call. My current code doesn't work properly, in that the value of the lskey variable has been altered by further loop iterations.

Here is the code:

for (var i = 0, len = localStorage.length; i < len; i++) {
        var lskey = localStorage.key(i);
        if (lskey.substr(0, 4) === 'form') {
            var postdata = localStorage.getItem(lskey); // Get the form data
            $.ajax({
                type: "POST",
                async: "false",
                url: "/Profile/PostForm",
                data: postdata,
                success: function (data) {
                    $('#rollinginfo').append('<br>' + data + ',key=' + lskey);
                    localStorage.removeItem(lskey); // Remove the relevant localStorage entry
                }
            , error: function (data) { $('#rollinginfo').append('<br />ERR:' + data); }
            });


        }
    } 

The problem is that lskey is being altered each time the loop executes, and therefore the success callback does not have a reference to the value of lskey that existed at the time of the call.

How do I reference the correct value of lskey for each success callback?

Share Improve this question edited Jun 26, 2015 at 15:56 Sumurai8 20.8k11 gold badges69 silver badges102 bronze badges asked May 3, 2011 at 14:33 JourneymanJourneyman 10.3k16 gold badges84 silver badges131 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6
for (var i = 0, len = localStorage.length; i < len; i++) {
    var lskey = localStorage.key(i);
    if (lskey.substr(0, 4) === 'form') {
        var postdata = localStorage.getItem(lskey); // Get the form data
        $.ajax({
            type: "POST",
            async: "false",
            url: "/Profile/PostForm",
            data: postdata,
            local_lskey: lskey
            success: function (data) {
                $('#rollinginfo').append('<br>' + data + ',key=' + lskey);
                localStorage.removeItem(this.local_lskey); // Remove the relevant localStorage entry
            }
        , error: function (data) { $('#rollinginfo').append('<br />ERR:' + data); }
        });
    }
}

This should work.

In the end I added the key info to the server posting, and then returned it from the server in JSON format so the success function could then simply refer to the key contained in the server response.

Have you considered chaining the AJAX calls? Basically you can make one AJAX call, process the result, modify lskey, etc. Then when you are ready, increment i and issue the second AJAX call. Loop this way instead of using the for loop...

You could put your ajax call into its own function and pass the lskey and postData values in. That way localStorage.removeItem(lskey) will refer to the lskey variable in the context of the function rather than the context of the loop.

Example

Declare the function -

function postForm(postdata, lskey) {
  $.ajax({
    type: "POST",
    async: "false",
    url: "/Profile/PostForm",
    data: postdata,
    success: function(data) {
      $('#rollinginfo').append('<br>' + data + ',key=' + lskey);
      localStorage.removeItem(lskey); // Remove the relevant localStorage entry
    },
    error: function(data) {
      $('#rollinginfo').append('<br />ERR:' + data);
    }
  });
}

Then you can call your function from your loop -

for (var i = 0, len = localStorage.length; i < len; i++) {
  var lskey = localStorage.key(i);
  if (lskey.substr(0, 4) === 'form') {
    var postdata = localStorage.getItem(lskey); // Get the form data
    postForm(postdata, lskey);
  }
}

You could also declare the function just before the loop (assigning it to a variable) and then call it within the loop.

var postForm = function(postdata, lskey) {
  $.ajax({
    type: "POST",
    async: "false",
    url: "/Profile/PostForm",
    data: postdata,
    success: function(data) {
      $('#rollinginfo').append('<br>' + data + ',key=' + lskey);
      localStorage.removeItem(lskey); // Remove the relevant localStorage entry
    },
    error: function(data) {
      $('#rollinginfo').append('<br />ERR:' + data);
    }
  });
}
for (var i = 0, len = localStorage.length; i < len; i++) {
  var lskey = localStorage.key(i);
  if (lskey.substr(0, 4) === 'form') {
    var postdata = localStorage.getItem(lskey); // Get the form data
    postForm(postdata, lskey);
  }
}
发布评论

评论列表(0)

  1. 暂无评论