第二次加载时 XMLHttpRequest 状态 0
当我尝试使用 XMLHttpRequest 从同一域加载一些 .txt 格式的数据时,遇到一个有趣的问题。 我正在尝试加载数据,解析它,然后将其存储在 localStorage 中。
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var temp;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
temp = xmlhttp.responseText;
}else{
alert("readyState: " + xmlhttp.readyState + "status: " + xmlhttp.status);
}
}
xmlhttp.open("GET","data/somedata.txt", false);
xmlhttp.send();
此代码仅在我清理历史记录和缓存时才有效;但是,在第二次单击同一链接时,由于某种原因,我会收到“Readystate:4,状态0”。
这和localStorage有什么关系吗?
if (!localStorage.somedata || localStorage.somedata.count(':') !== somedata.count(':')) {
localStorage.somedata = temp;
}
window.somedata = JSON.parse(localStorage.somedata);
I am experiencing an interesting issue when I am trying to load some data in .txt format from the same domain using XMLHttpRequest.
I am trying to load the data, parse it and then store it in localStorage
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var temp;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
temp = xmlhttp.responseText;
}else{
alert("readyState: " + xmlhttp.readyState + "status: " + xmlhttp.status);
}
}
xmlhttp.open("GET","data/somedata.txt", false);
xmlhttp.send();
This code only works if I clean the history and cache; however, on second click of the same link, I would received "Readystate: 4, status 0" for some reason.
Does this has anything to do with localStorage?
if (!localStorage.somedata || localStorage.somedata.count(':') !== somedata.count(':')) {
localStorage.somedata = temp;
}
window.somedata = JSON.parse(localStorage.somedata);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
状态码为零的原因有两个。
在你的情况下,我假设它是#2。如果您使用按钮或链接进行 Ajax 调用,请确保使用
preventDefault
或return false
取消单击操作。There are two causes of status code of zero.
In your case I would assume it is #2. If you are using a button or a link to make the Ajax call, make sure to cancel the click action with either
preventDefault
orreturn false
.听起来像是缓存问题。尝试切换到 POST 方法,或将时间戳附加到 GET 请求查询字符串,看看是否会阻止缓存。
或者:
编辑:如果这些不起作用,请修改您的服务器配置以发送该文件或类型的适当响应标头,以不缓存响应。即:
缓存控制:无缓存
Sounds like a caching issue. Try either switching to a
POST
method, or appending a timestamp to theGET
request querystring and see if that prevents the caching.or:
Edit: If those don't work, modify your server configuration to send appropriate response headers for that file or type to not cache the response. Ie:
Cache-Control: no-cache
在打开新请求之前尝试
xmlhttp.abort()
。这是一个漫长的尝试,但值得一试。
Try
xmlhttp.abort()
before opening a new request.It's a long shot but worth the try.