您的位置:首页 > 理论基础 > 计算机网络

AJAX问题之XMLHttpRequest.status = 0&&XMLHttpRequest.readyState=1

2017-01-07 17:57 591 查看
这几天看ajax,发现个问题,XMLHttpRequest对象的readyState一直=1,status =0。

问题是这样的,一开始执行不下去,FF又没有提示错误,并且没有W3C上实例提示的

onreadystatechange按步骤触发,不知道是哪的问题,加了alert()测试,一直显示XMLHttpRequest对象的readyState一直==1,status ==0,后来再加
if (xhr.readyState==4)判断条件后,后面的代码能正常提示,说明readyState 的状态是变化的,但是status=0,
用chrome找到了提示错误:
ajax_test.html:32 XMLHttpRequest cannot load file:///E:/workspace-sts-3.8.2.RELEASE/ajax_test01/WebContent/ajax.do. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
是跨域问题。
所以直接http://localhost:8080/ajax_test01/ajax_test.html访问后正常。




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
window.onload = init;
function init() {
var bt = document.getElementById("getData");
bt.onclick = getData;

}

function getData() {
var xhr = createXMLHttpRequest();
alert(xhr);
xhr.open("GET","ajax.do",true);
//alert(this.value);
alert(xhr.readyState);
alert(xhr.status);
xhr.onreadystatechange=function() {
if (xhr.readyState==4) {
alert(xhr.readyState);
alert(xhr.status);
alert(document.getElementById("sd"));
document.getElementById("sd").innerHTML = xhr.responseText;
}
}

xhr.send();

}

function createXMLHttpRequest() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHttp")
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
alert("你使用的浏览器不支持XMLHttpRequest");
}
}
</script>
<input type="button" id="getData" value="获取数据">
<div id="sd"></div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: