答案 0 :(得分:3)
你的var = xmlhttp;在switchText范围之外,因此它未定义并引发错误。
试试这个
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function switchText()
{loadXMLDoc();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="switchText()">Change Content</button>
</body>
</html>
答案 1 :(得分:2)
我认为你遇到的问题是你没有验证你的代码,甚至是否有匹配的大括号(提示,你没有!)
移动open并将命令发送回第一个函数并删除额外的大括号shoudl工作。
以下应该有效:
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
function switchText()
{
loadXMLDoc();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="switchText()">Change Content</button>
</body>
</html>
希望有所帮助
奥利
答案 2 :(得分:0)
我认为问题出在ajax_object.html文件中的以下行:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
如果您使用上面的行运行文件并查看“显示页面源”, 很明显,'请求&amp;响应'标题有它的 - 状态和代码---设置为空
So, delete the line and you will get:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script-->
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
If you run this code it will output the ajax_info.txt file.