[英]Why XmlHttpRequest readyState = 2 on 200 HTTP response code
So I'm using plain javascript (no jquery), to send a file to the server. 因此,我使用普通的javascript(无jquery)将文件发送到服务器。 Server script PHP returns status code 200 at the end, but instead javascript is getting readyState == 2. 服务器脚本PHP最后返回状态码200,但javascript却准备就绪状态== 2。
The PHP code sends back status code 200: PHP代码发送回状态代码200:
header('X-PHP-Response-Code: 200', true, 200);
exit;
The javascript is doing: JavaScript正在执行:
request.onreadystatechange = function() {
if (request.readyState == 4) {
var message;
switch(request.status) {
case '200':
message = "Data uploaded successfully.";
break;
case '406':
message = "Incorrect file format. Please try again.";
break;
case '410':
message = "Unexpected error. Please contact support.";
break;
default:
break;
}
status_message_container.innerHTML = message;
submit_button.disabled = false;
}
else {
alert( "Unexpected error: " + this.statusText + ".\nPlease try again");
}
};
request.send(formData);
Even know the HTTP 200 status code comes back correctly (I get 'OK') on frontend. 甚至知道HTTP 200状态代码在前端正确返回(我得到“确定”)。 The JS script is seeing readyState==2
(ie else block always hit) JS脚本看到readyState==2
(即,其他块总是命中)
My understanding is that a server status code of 200 should give readyState == 4
?? 我的理解是,服务器状态代码200应该给readyState == 4
?
Firstly, onreadystate
isn't just fired once. 首先, onreadystate
不会被触发一次。 It's fired multiple times, you need to be able to handle that. 它被解雇了多次,您需要能够处理它。 These are the codes you need to handle: 这些是您需要处理的代码:
0 UNSENT - open()has not been called yet 0 UNSENT- 尚未调用open()
1 OPENED - send()has not been called yet 1 OPENED- send()尚未被调用
2 HEADERS_RECEIVED - send() has been called, and headers and status are available 2 HEADERS_RECEIVED- 已调用send(),并且头和状态可用
3 LOADING Downloading; 3 LOADING下载; - responseText holds partial data -responseText保存部分数据
4 - The operation is complete 4- 操作完成
Your code is hitting the else block on readyState == 2
(headers received) and assuming that is an error status when it's not. 您的代码在readyState == 2
(接收到的标头)上击中else块,并假设不是时为错误状态。
You error check should be inside the request.readyState == 4
check. 您的错误检查应该在request.readyState == 4
检查内。 That way, the request is complete but there could also have been an error: 这样,请求已完成,但也可能出现错误:
if (request.readyState == 4) {
switch(request.status) {
case '200':
message = "Data uploaded successfully.";
break;
// Error handling here
default: alert( "Unexpected error: " + this.statusText + ".\nPlease try again"); break;
}
}
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.