所以,我使用的是普通的JavaScript(无jQuery的),发送文件到服务器。服务器脚本PHP的返回状态code 200在最后,而是JavaScript是越来越readyState的== 2。
So I'm using plain javascript (no jquery), to send a file to the server. Server script PHP returns status code 200 at the end, but instead javascript is getting readyState == 2.
PHP的code发送回状态code 200:
The PHP code sends back status code 200:
header('X-PHP-Response-Code: 200', true, 200);
exit;
的JavaScript是这样做的:
The javascript is doing:
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);
即使知道HTTP 200状态code回来正确的(我得到'OK')的前端。该JS脚本是看到 readyState的== 2
(即else块总是命中)
Even know the HTTP 200 status code comes back correctly (I get 'OK') on frontend. The JS script is seeing readyState==2
(i.e. else block always hit)
我的理解是,200的服务器状态code应该给的readyState == 4
??
My understanding is that a server status code of 200 should give readyState == 4
??
首先, onreadystate
不只是触发一次。它的发射多次,你需要能够处理。这是C $ CS,你需要处理$:
Firstly, onreadystate
isn't just fired once. It's fired multiple times, you need to be able to handle that. These are the codes you need to handle:
0 UNSENT - 的的open()没有被调用尚未的 1打开 - 发送()没有被调用尚未的 2 HEADERS_RECEIVED - 发送()被调用,头和状态都可以的 3 LOADING下载; - 的responseText持有的部分数据的 4 - 的的操作完成的
0 UNSENT - open()has not been called yet 1 OPENED - send()has not been called yet 2 HEADERS_RECEIVED - send() has been called, and headers and status are available 3 LOADING Downloading; - responseText holds partial data 4 - The operation is complete
您code是打别人块 readyState的== 2
(接收的头),并假设这是一个错误的状态时,它不是。
Your code is hitting the else block on readyState == 2
(headers received) and assuming that is an error status when it's not.
您错误校验应该是 request.readyState == 4
检查里面。这样,请求完成但也可能是一个错误:
You error check should be inside the request.readyState == 4
check. 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 /文档/网页/ API / XMLHtt prequest