Why XmlHttpRequest readyState = 2 on 200 HTTP response code
所以我使用纯 javascript(没有 jquery)将文件发送到服务器。服务器脚本 PHP 最后返回状态码 200,但 javascript 正在准备就绪状态 == 2.
PHP 代码返回状态码 200:
1 2 | header('X-PHP-Response-Code: 200', true, 200); exit; |
javascript 正在做的事情:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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 +".\ Please try again"); } }; request.send(formData); |
即使知道 HTTP 200 状态代码在前端正确返回(我得到"OK")。 JS 脚本看到
我的理解是服务器状态码 200 应该给
首先,
0 UNSENT - open() 尚未被调用
1 OPENED - 尚未调用 send()
2 HEADERS_RECEIVED - send() 已被调用,并且标头和状态可用
3 LOADING 下载; - responseText 保存部分数据
4 - 操作完成
您的代码正在点击
你的错误检查应该在
1 2 3 4 5 6 7 8 9 10 | if (request.readyState == 4) { switch(request.status) { case '200': message ="Data uploaded successfully."; break; // Error handling here default: alert("Unexpected error: " + this.statusText +".\ Please try again"); break; } } |
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest