问题描述:

I don't know why xmlhttp.response is returning undefined after contacting the php file.

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";

?>

It should alert "hi" every 3 seconds, but it alerts "undefined" every 3 seconds.

网友答案:

Note the capital T in responseText. So it should be xmlhttp.responseText.

网友答案:

In javascript, "undefined" means the variable you tried to access is not defined, i.e., it doesn't exist. When you see that, you should check right away for typos. In this case, xmlhttp.responsetext should be xmlhttp.responseText. The lowercase property you selected does not exist.

In WebKit browsers like Chrome and Safari (and I'm sure in others, but those are the ones I use) you can also check your variable names in the console. Google how to use the developer tools in your browser. When you're having trouble referencing a property on an object like you are now, it's often helpful to type/log the object name into the console, which will then show you a list of all its properties. For instance, if you add console.log(xmlhttp) to your script, it will show the object and all its properties in the console, and you can see that the property you want is responseText, not responsetext.

相关阅读:
Top