我不知道为什么xmlhttp.response在联系php文件后返回undefined。
index.php
<script language="Javascript">
var countdown;
countdown = setInterval(function(){
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(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responsetext);
}
}
xmlhttp.open("GET","updateindex.php?id=8",true);
xmlhttp.send();
},3000);
</script>
updateindex.php
<?php
echo "hi";
?>
它应该每3秒提醒一次"嗨",但它每3秒警告一次"未定义"。
注意responseText中的大写字母T。所以它应该是xmlhttp.responseText
。
在javascript中,"undefined"表示您尝试访问的变量未定义,即不存在。当你看到这一点时,你应该立即检查拼写错误。在这种情况下,xmlhttp.responsetext
应该是xmlhttp.responseText
。您选择的小写属性不存在。
在像Chrome和Safari这样的WebKit浏览器中(我相信在其他浏览器中,但我使用的是这些浏览器),你也可以在控制台中检查你的变量名。谷歌如何在浏览器中使用开发工具。当你像现在这样在引用对象的属性时遇到困难时,在控制台中键入/记录对象名称通常会很有帮助,然后控制台会向你显示其所有属性的列表。例如,如果您将console.log(xmlhttp)
添加到脚本中,它将在控制台中显示对象及其所有属性,并且您可以看到您想要的属性是responseText
,而不是responsetext
。