来自" DOM脚本网页设计的一个例子js是文档对象模型" ajax.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Ajax</title>
</head>
<body>
<div id="new"></div>
<script src="scripts\addLoadEvent.js"></script>
<script src="scripts\getHTTPObject.js"></script>
<script src="scripts\getNewContent.js"></script>
</body>
</html>
addLoadEvent.js
function addLoadEvent(func)
{
var oldonload = window.onload;
if(typeof window.onload != 'function')
{
window.onload = func;
}
else{
window.onload = function(){
oldonload();
func();
}
}
}
getHttpObject,JS
function getHTTPObject()
{
if(typeof XMLHttpRequest == 'undefined')
XMLHttpRequest = function(){
try{return new ActiveXObject('Msxml2.XMLHTTP.6.0');}
catch (e) {}
try{return new ActiveXObject('Msxml2.XMLHTTP.3.0');}
catch (e) {}
try{return new ActiveXObject('Msxml2.XMLHTTP');}
catch (e) {}
return false;
}
return new XMLHttpRequest();
}
getNewContent.js
function getNewContent()
{
var request = getHTTPObject();
if(request){
request.open("GET","example.txt",true);
request.onreadystatechange = function(){
if(request.readyState == 4){
if(request.status == 0){
var para = document.createElement("p");
var txt = document.createTextNode(request.responseText);
para.appendChild(txt);
document.getElementById('new').appendChild(para);
}
}
};
request.send(null);
}else{
alert('sorry,your browser doesn\'t support XMLHTTPRequest');
}
}
addLoadEvent(getNewContent);
example.txt
和ajax.html
位于同一目录中,request.status=0
,
responseText
始终为空。我的代码出了什么问题?
答案 0 :(得分:0)
当我使用chrome或IE时,我遇到了同样的问题。但是,当我切换到Firefox时,它真的很棒!有人说这是因为Ajax基于HTTP协议。 IE或Chrome在HTTP和FILE协议之间会有错误。 Firefox可以兼容(细节对我来说太复杂了),所以我建议使用Firefox~ 另外,请检查脚本中没有拼写错误。