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/