开发者

(Why) does this ajax queue overwrite response data?

开发者 https://www.devze.com 2023-02-14 06:36 出处:网络
I use the ajax-request queue as posted here: Wait until all jQuery Ajax requests are done? Now i wrote the following code to implement it:

I use the ajax-request queue as posted here: Wait until all jQuery Ajax requests are done?

Now i wrote the following code to implement it:

for (var i=0; i<3; i++) {
    $.ajaxQueue({
        url: '/action/',
        data: {action:'previous',item:i*-1},
        type: 'GET',
        success: function(data) {
            $('.item-history .itemlist').prepend(data['item_add']);
            $('.item-history .itemlist:first .index').html(data['newitemindex']);
            //alert(data['newitemindex'])       
        };
    });

As long as i use the alert to proof the response from the server, everything works fine. But as soon as i run the code, as shown, without the alert, data['newitemindex'] behaves as it was a global variable - it always returns the value of 开发者_如何学Pythonthe last item.

I tried to set up a jsfiddle on this, but as i have never used that site, i could not get the ajax to work. If somebody wants to have a look at it anyway: http://jsfiddle.net/marue/UfH5M/26/


Your code is setting up three ajax calls, and then applying the result of each of them to the same elements (there's no difference in the selectors you use inside your success function). For the $('.item-history .itemlist') elements, you should see the result of each call prepended to the elements because you're using prepend(), but for the $('.item-history .itemlist:first .index') elements, you're using html() which replaces the elements' contents, and so for those you'll see the result of the last call that completes.


Off-topic: To fix that, you're probably going to want to use your loop variable in some way in the success function. That could lead you to a common mistake, so here's an example of the mistake and how to avoid it.

Let's say I have these divs:

<div id='div1'></div>
<div id='div2'></div>
<div id='div3'></div>

And I want to use three ajax calls to populate them when I click a button, using a loop counter from 1 to 3. I might think I could do it like this:

$('#btnGo').click(function() {
  var i;

  for (i = 1; i <= 3; ++i) {
    $.ajax({
      url: "/agiba4/" + i,
      dataType: "text",
      success: function(data) {
        // THIS NEXT LINE IS WRONG
        $('#div' + i).html(data);
      },
      error: function(xhr, status, err) {
        $("<p/>").html(
          "Error, status = " + status + ", err = " + err
          ).appendTo(document.body);
      }
    });
  }
});

Live example (which fails)

But (as indicated) that doesn't work. It doesn't work because each success function we create has an enduring reference to the i variable, not a copy of its value as of when the success function was created. And so all three success functions see the same value for i, which is the value when the function is run — long after the loop is complete. And so (in this example), they all see the value 4 (the value of i after the loop finishes). This is how closures work (see: Closures are not complicated).

To fix this, you set it up so the success function closes over something that isn't going to be updated by the loop. The easiest way is to pass the loop counter into another function as an argument, and then have the success function close over that argument instead, since the argument is a copy of the loop counter and won't be updated:

$('#btnGo').click(function() {
  var i;

  for (i = 1; i <= 3; ++i) {
    doRequest(i);
  }

  function doRequest(index) {
    $.ajax({
      url: "/agiba4/" + index,
      dataType: "text",
      success: function(data) {
        $('#div' + index).html(data);
      },
      error: function(xhr, status, err) {
        $("<p/>").html(
          "Error, status = " + status + ", err = " + err
          ).appendTo(document.body);
      }
    });
  }
});

Live example

0

精彩评论

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