我的AJAX程序怎么运行不了?

来源:百度知道 编辑:UC知道 时间:2024/05/08 19:15:35
我有一个AJAX程序,其中一个是html文档,另一个是xml文档
html文档代码如下:
<html>
<head>
<title>使用responseText</title>

<script type="text/javascript">
var xmlHttp;

function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}

function startRequest() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "15-12.xml", true);
xmlHttp.send(null);
}

function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
</script>

if(xmlHttp.status==200 || xmlHttp.status==0) {
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
代码直接在本地运行(如D:\test\test.html),status属性不管是在“成功”还是“页面未找到”的情况下,都返回的是0,而不是200和404。这个时候如果还用if(xmlHttp.status==200)来判断运行,则会毫无结果。如果要在本地测试,最好写成if(xmlHttp.status==200 || xmlHttp.status==0)的形式来判断。

具体原理一时说不完,这样吧。

xmlHttp.open("GET", "15-12.xml", true);
//改为 xmlHttp.open("GET", "15-12.html", true);

把15-12.xml别存为15-12.html

OK!

<input type="button" value="搜索" onClick="startRequest();"/>
这里多了个分号。改成:
<input type="button" value="搜索" onClick="startRequest()"/>