I wrote the following simple javascript code
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head> <title>ajax</title> </head>
<body>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
var url = "http://localhost/javascript/test.php";
xhr.open("GET", url);
alert(xhr);
xhr.send(null);
xhr.onreadystatechange = function () {alert("change");}
alert(xhr.responseText);
</script>
</body>
</html>
the result shows xhr.responseText is empty.
But following javascript code works fine. Why?
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>ajax</title></head>
<body>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
var url = "http://localhost/javascript/test.php";
xhr.open("GET", url);
xhr.send(null);
xhr.onreadystatechange =
function () {
if (xhr.readyState == 4) alert(xhr.responseText);
};
</script>
</body>
</html>
Following is the simple PHP code: test.php
<?php
echo date("F j, Y, H:i:s");
When an answer comes from the server, the browser will fire the object’s onreadystatechanged event, causing the function you attached to it, to be fired, what you need to do in your first example is put this line :
inside the function you attach to the onreadystatechanged event.
otherwise the browser will just process the line immediately after sending the request.
In addition, you must check that the readystate is 4 (4: request finished and response is ready), and its also worth it to check that the status is 200, which means that everything’s ok.