开发者

HTML data from multiple ajax requests to javascript array

I'm trying to pre-load some html content using AJAX and jQuery. The AJAX callback function adds the data to an associative array. I'm fine if I do each request individually:

var contentArray = new Object();

var urlA = "includes/contentA.php";
var urlB = "includes/contentB.php";
var urlC = "includes/contentC.php";

$.get(urlA, function(htmlA) {
    contentArray["A"] = htmlA;
});
$.ge开发者_如何学编程t(urlB, function(htmlB) {
    contentArray["B"] = htmlB;
});
$.get(urlC, function(htmlC) {
    contentArray["C"] = htmlC;
});

Since I am likely to have a few of these (more than three), I tried to do it a for loop:

var contentArray = new Object();
var pages = new Object();

pages["A"] = "includes/contentA.php";
pages["B"] = "includes/contentB.php";
pages["C"] = "includes/contentC.php";

for (var key in pages) {
    var URL = pages[key];
    $.get(URL, function(html) {
        contentArray[key] = html;
    });
}

However, this doesn't work. contentArray only has one property containing html data, rather than three. I'm knew to jQuery, particularly the AJAX stuff, so both explanations and solutions (similar or different-method-same-result) are welome.

By the way, I'm aware that one larger AJAX request is preferable to multiple small ones, but I'm trying to retain compatibility for users without JS enabled, and the current php includes are convenient. Any suggestions as how I might satisfy both these requirements are also very welcome.

Thanks.


The callback function for an AJAX request doesn't run until the request returns. In your case each callback function will use key as it exists in the current context, and since there's no key variable in it's local scope it will use the nearest it can find, the key in your for loop.

The problem is by the time the AJAX requests return, the for loop has been fully iterated over and key is equal to the last key in the array. Thus each of the callback functions will receive the same key, overwriting the previous value in your contentArray.

If you're using jQuery 1.5.1 or above a quick and dirty solution (one that doesn't involve changing the current structure of your PHP files) might be to try the following:

for (var key in pages) {
  var URL = pages[key];

  $.ajax({
    url: URL,
    xhrFields: {
      'customData': key
    },
    success: function(html, statusText, jqXHR) {
      contentArray[jqXHR.customData] = html;
    }
  });
}

I haven't tested that but according to the documentation page it should work. All you're doing is using the request object created by jQuery to pass your variable along to the callback function.

Hope that helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜