Array loses its contents after exiting xmlhttpRequest [closed]
-
08-06-2021 - |
문제
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:
- Set
i = 0
- Check,
i < count
, is true, continue for loop - Web request A starts
- Print
result[0]
- Set
i = 1
- Check,
i < count
, is true, continue for loop - Web request B starts
- Print
result[1]
- Set
i = 2
- Check,
i < count
, is false, exit for loop - ... time passes ...
- Web request A completes, sets
result[i]
, so setresult[2] = "foo"
- Web request B completes, sets
result[i]
, so setresult[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