문제

I know that is a stupid question but i want to ask how i can save content to an array inside a xmlhttpRequest and use them after.

onlinestatus = new Array(count);
for (var i = 0; i <= count; i++) {
    GM_xmlhttpRequest({
        method: 'GET',
        url: 'http://www.website.com/player/' + player[i] + '/details.php',
        onload: function(responseDetails) {
            buddypage = jQuery(responseDetails.responseText);
            online = jQuery("span#OnlineStatus", buddypage);
            onlinestatus[i] = online.text();
        }
    });
    GM_log("Current: " + onlinestatus[i]);
}​
도움이 되었습니까?

해결책

Two things will stop this working: the web request will be asynchronous, and the values will all be stored in the same location in the array.

Here's the order things will happen, assuming count = 2:

  1. Set i = 0
  2. Check, i < count, is true, continue for loop
  3. Web request A starts
  4. Print result[0]
  5. Set i = 1
  6. Check, i < count, is true, continue for loop
  7. Web request B starts
  8. Print result[1]
  9. Set i = 2
  10. Check, i < count, is false, exit for loop
  11. ... time passes ...
  12. Web request A completes, sets result[i], so set result[2] = "foo"
  13. Web request B completes, sets result[i], so set result[2] = "bar"

That means that the result array ends up as [undefined, undefined, "bar"]. The last value of the array could be foo or bar, depending on which web request finishes first. Either way, by the time the web requests complete, i will have already been set to the wrong value, and the results will have already been logged, so it will look like the results array is empty.

다른 팁

You should know that ajax request returns at some unknown time in the future.
You can use the array only in the callback of the ajax request.

AJAX- Asynchronous JavaScript and XML

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top