Xmlhttprequest Launches Multiple Times Without Initiating The Onreadystatechange Function
The userscript in question: http://userscripts.org/scripts/show/130532 After the site it's been made for has been updated to HTML5, I had to update the script. However, it's got a
Solution 1:
You're using several variables without declaring these locally:
var ..., found, xhr1, xhr2, cstatus, ui, pg;
...
functiondoIndex(pg) {
...
xhr1 = newXMLHttpRequest();
// ^^^^ No var !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
...
xhr1.onreadystatechange = function() {
if (xhr1.readyState === 4) { ... }
if (found) {
...
} else {
if (pg < 15) {
doIndex(pg + 1); // <-- !!!!!!!!!!!!!!!!!!
} else { ...
xhr2 = newXMLHttpRequest();
...
xhr2.onreadystatechange = function() { ... };
xhr2.send(null);
}
}
};
xhr1.send(null);
}
} ...
doIndex(0); // Initiate the doom
First, you assign a new XHR instance to a non-local xhr1
variable.
Then, you add a readystatechange
event handler, in which the following happens:
- Initially,
readyState
is not four, sofound
is false. Sincepg
starts at 0,doIndex(pg + 1)
is called. Now,xhr1
gets overwritten by a new XHR instance. - This continues, until
pg
reaches 15. Then,pg < 15
is false, and the horror starts:xhr1.onreadystatechange
fires multiple time during the request.pg < 15
is false, so theelse
block is evaluated, in which you launch several new XHR (xhr2
) requests...- All of the previous readystatechange events are still fired, because the requests haven't finished yet. In every event handler, you're comparing the value of
xhr1.readyState
, which refers to the state of the last createdxhr1
request. So, you're callingdoIndex(pg+1)
over and over again, which, oncepg
has reached 15, creates new XHR (xhr2
) instances.
To fix the problem, declare the variables in the function, and wrap the whole onreadystatechange
block in if (xhr1.readyState == 4)
(or use onload
instead of onreadystatechange
).
functiondIndex(pg) {
var xhr1, xhr2;
...
xhr1.onreadystatechange = function() {
if (xhr1.readyState === 4) {
/* ... */
}
};
...
Solution 2:
This helped based on answers:
let signupRequest = new XMLHttpRequest();
let url = "signup/" + inputMobile.value;
signupRequest.open("GET", url, true);
signupRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signupRequest.send();
signupRequest.onreadystatechange = function() {
if (signupRequest.readyState === 4) {
hideLoading();
if (signupRequest.status === 200) {
console.log("OK: " + status + " --- " + signupRequest.response);
} else {
console.log("NOK: " + status + " --- " + signupRequest.response);
}
}
};
Post a Comment for "Xmlhttprequest Launches Multiple Times Without Initiating The Onreadystatechange Function"