开发者

When will XmlHttpResponse.responseText be filled with reponse from the server?

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 ty开发者_开发技巧pe="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 :

alert(xhr.responseText);

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.


Similar to r0nny's answer, your first example gets processed before your ajax called has been returned. Using the onreadystatechange waits for the ajax response, then does what you need it to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜