第二次加载时XMLHttpRequest状态为0 [英] XMLHttpRequest status 0 on second load

查看:108
本文介绍了第二次加载时XMLHttpRequest状态为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用XMLHttpRequest从相同的域加载一些.txt格式的数据时,我遇到了一个有趣的问题。
我试图加载数据,解析它,然后将它存储在localStorage中

  var xmlhttp; 
//代码为IE7 +,Firefox,Chrome,Opera,Safari
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
//代码为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,status 0。

/ p>

  if(!localStorage.somedata || localStorage.somedata.count(':')!== somedata.count(': ')){
localStorage.somedata = temp;
}
window.somedata = JSON.parse(localStorage.somedata);


解决方案

状态码有两个原因。 / b>


  1. 通过文件协议进行调用。

  2. 页面正在刷新/导航,

在你的情况下,我会假定它是#2。如果您使用按钮或链接进行Ajax调用,请确保使用 preventDefault 返回false


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);

解决方案

There are two causes of status code of zero.

  1. Making calls from the file protocol.
  2. The page is refreshing/navigating away as the request is being made.

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 or return false.

这篇关于第二次加载时XMLHttpRequest状态为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆