Xmlhttprequest Is Always Calling "load" Event Listener, Even When Response Has Error Status
Solution 1:
This setup should work better for your needs:
var req = newXMLHttpRequest();
req.open('POST', '/upload_image');
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
alert(req.responseText);
elsealert("Error loading page\n");
}
};
req.send(formData);
In your code error callback is never called because it is only triggered by network-level errors, it ignores HTTP return codes.
Solution 2:
The load event is called whenever the server responds with a message. The semantics of the response don't matter; what's important is that the server responded (in this case with a 500 status). If you wish to apply error semantics to the event, you have to process the status yourself.
Solution 3:
Expanding on @rich remer's answer, here's how you could access the status yourself:
functionupload_image() {
var form = document.getElementById('upload_image_form');
var formData = newFormData(form);
var xhr = newXMLHttpRequest();
xhr.addEventListener("load", function(e) {
if(e.currentTarget.status < 400)
alert("Load callback - success!");
elsealert("Load callback - error!");
}, false);
xhr.addEventListener("error", function(e) {
alert("Error callback");
}, false);
xhr.open("POST", "/upload_image");
xhr.send(formData);
}
Please note accessing of the e.currentTarget.status
property of the response event (e
). Looks like the status is actually available via any of e.{currentTarget,target,srcElement}.status
- I'm not sure which one should be used as the best practice, though.
Solution 4:
functionget(url) {
returnnewPromise(function(succeed, fail) {
var req = newXMLHttpRequest();
req.open("GET", url, true);
req.addEventListener("load", function() {
if (req.status < 400)
succeed(req.responseText);
elsefail(newError("Request failed: " + req.statusText));
});
req.addEventListener("error", function() {
fail(newError("Network error"));
});
req.send(null);
});
}
code from EJS by the example code it is clear that network error has no response, it trigger error event. response trigger load event and you have to decide what to do with the response status
Post a Comment for "Xmlhttprequest Is Always Calling "load" Event Listener, Even When Response Has Error Status"