XHR responseText is empty string

2019-01-20 12:22发布

问题:

Html Page:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>xhr</title>
</head>
<body>
    <script>
        var xhr_test = new XMLHttpRequest();
        xhr_test.open("GET","xhrtest",true);
        xhr_test.send();
        alert(xhr_test.responseText);
    </script>
</body>
</html>

The main.py file:

import webapp2
from handlers import cookies,pages
application = webapp2.WSGIApplication([
        ('/xhr',pages.XHR),
        ('/xhrtest', cookies.XHRTest)
        ],
            debug=True)

The Request handlers:

class XHRTest(webapp2.RequestHandler):
    def get(self):
        self.response.write('0')

and,

class XHR(webapp2.RequestHandler):
    def get(self):
        f = open('static/html/xhr.html','r')
        self.response.write(f.read())

Now, when I hit upon the url localhost:8080/xhrtest the browser promptly shows the response 0 as the page's content.

Hitting the url localhost:8080/xhr which indirectly hits /xhrtest, pops up an empty string in the alert box (the responseText is an empty string) but checking chrome's response tab under the network tab, I can see that the request's response is 0.

So why is xhr_test.responseText not able to display the same response?

回答1:

The call to send is asynchronous (you've set the 'async' parameter to true), which means that your alert is happening immediately, before the request finishes. You should add an event-listener to xhr.onreadystatechange and use the response within that.

Changing the 'true' to 'false' would make this simple example work, but is not a good idea in the general case.

The MDN page on Ajax explains how XMLHttpRequest should be used.