javascript - XHR responseText 为空字符串

标签 javascript google-app-engine xmlhttprequest webapp2

HTML 页面:

<!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>

main.py 文件:

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

请求处理程序:

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

和,

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

现在,当我访问 url localhost:8080/xhrtest 时,浏览器会立即显示响应 0 作为页面内容。

点击url localhost:8080/xhr间接点击/xhrtest,在alert框中弹出一个空字符串(responseText为空字符串)但是检查chrome 的网络选项卡下的响应选项卡,我可以看到请求的响应是 0

那么为什么 xhr_test.responseText 无法显示相同的响应?

最佳答案

发送调用是异步的(您已将“async”参数设置为 true),这意味着您的警报会在请求完成之前立即发生。 您应该向 xhr.onreadystatechange 添加事件监听器并使用其中的响应。

将“true”更改为“false”会使这个简单示例起作用,但在一般情况下不是一个好主意。

MDN page on Ajax解释应该如何使用 XMLHttpRequest。

关于javascript - XHR responseText 为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19549269/

相关文章:

javascript - npm 参数导致 "Insufficient number of arguments or no entry found"

javascript - 是否可以在表中找到 td 的数量,然后使用 Javascript 在表标记内应用 col 宽度?

google-app-engine - 如何在 GCS 中通过元数据查询文件?

http - 从列表中替换 HTTP POST URL 中的变量

xmlhttprequest - dart,您如何阅读http请求的内容主体?

javascript - 单击父按钮单击时如何重置子输入的数据和 View ?

javascript - 通过JS和Jquery获取CSS元素值

java - JAVA GAE 的 OpenID 消费者

google-app-engine - 是否可以将多个域映射到单个 Google App Engine 应用程序?

javascript - "xmlns:xmpp"和 "xmpp:xmlns"有什么区别?