我偶尔会看到一个失败的XMLHttpRequest.send()。从Chrome的网络面板我看到状态为0 - 请参阅下面的.har文件。运行send()的代码在99%的时间内成功,但偶尔(~1 / 300)它返回0。
我的问题是:我怎么抓住这个?是否有回调会抓住它?
我目前正在使用onload和onerror:
var xhr = new XMLHttpRequest();
xhr.onload = function(){};
xhr.onerror = function(){};
这两个都没有被调用,所以它无声地失败了。 还有一些需要注意的事项:
这是.har文件输出。 ## =节录。
{
"startedDateTime": "2013-03-30T23:52:20.972Z",
"time": 97,
"request": {
"method": "GET",
"url": "https://www.#######.com/project/auth_upload?to_sign=PUT%0A%0A%0A%0Ax-amz-date%3ASat%2C%2030%20Mar%202013%2023%3A52%3A20%20GMT%0A/s3.#####.com/######.mp4%3FpartNumber%3D50%26uploadId%3D#################.w--&asset_id=#############&project_id=###########",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Referer",
"value": "https://www.######.com/console/###########"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.152 Safari/537.22"
}
],
"queryString": [
{
"name": "to_sign",
"value": "PUT%0A%0A%0A%0Ax-amz-date%3ASat%2C%2030%20Mar%202013%2023%3A52%3A20%20GMT%0A/s3.#######.com/############.mp4%3FpartNumber%3D50%26uploadId%3D##############"
},
{
"name": "asset_id",
"value": "###########"
},
{
"name": "project_id",
"value": "###############"
}
],
"cookies": [],
"headersSize": 595,
"bodySize": 0
},
"response": {
"status": 0,
"statusText": "",
"httpVersion": "HTTP/1.1",
"headers": [],
"cookies": [],
"content": {
"size": 0,
"compression": 0
},
"redirectURL": "",
"headersSize": 13,
"bodySize": 0
},
"cache": {},
"timings": {
"blocked": 0,
"dns": -1,
"connect": -1,
"send": -1,
"wait": -1,
"receive": null,
"ssl": -1
}
}
谢谢,
汤姆
答案 0 :(得分:1)
似乎statusCode 0表示响应为空甚至标题都没有发送,这是很难弄清楚的,你需要自己找出它
但是您说响应没有到达您的函数是因为您正在使用load
和error
事件来侦听响应,实际上您不应该完全依赖于这两个错误,考虑在请求完成之前发生超时的情况,然后'timeout'事件将被触发而不是'错误'
相反,您应该使用readystatechange
事件,该事件将在每次状态更改请求时被调用,您还可以跟踪与未收到响应相关的超时或错误
httpRequest.onreadystatechange = stateChangeHandler;
stateChangeHandler = function() {
// The readyState can be 4 values:
// 0 - uninitialized
// 1 - loading
// 2 - loaded
// 3 - interactive
// 4 - complete
//
// readyState 0 - 3 can be completely ignored by us, as they are only updates
// about the current progress. Only on readyState 4, should we continue and
// start checking for the response status.
if (xmlHttpRequest.readyState != 4) {
return;
}
// Check HTTP Response code
if (xmlHttpRequest.status != 200) {
// response is ok process it
} else {
// there was some error
}
}
<强>参考:强>