[英]AJAX - Not getting a simple php response(returns “undefined”)
我不知道为什么xmlhttp.response在联系php文件后返回未定义。
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秒提醒一次“ hi”,但每3秒提醒一次“ undefined”。
注意responseText中的大写字母T。 因此它应该是xmlhttp.responseText
。
在javascript中,“未定义”表示您尝试访问的变量未定义,即该变量不存在。 当您看到该错误时,应立即检查是否有错别字。 在这种情况下, xmlhttp.responsetext
应该是xmlhttp.responseText
。 您选择的小写字母属性不存在。
在Chrome和Safari等WebKit浏览器中(我敢肯定在其他浏览器中,但我使用的是那些),您还可以在控制台中检查变量名。 Google如何在浏览器中使用开发人员工具。 当您像现在这样在引用对象时遇到麻烦时,在控制台中键入/记录对象名称通常会很有帮助,然后控制台将向您显示所有属性的列表。 例如,如果将console.log(xmlhttp)
添加到脚本中,它将在控制台中显示该对象及其所有属性,并且可以看到所需的属性是responseText
,而不是responsetext
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.