XHR responseText是空字符串 [英] XHR responseText is empty string
问题描述
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>
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
为该页面的内容。
点击 / xhrtest $
localhost:8080 / xhr
c $ c>,在警告框中弹出一个空字符串(responseText是一个空字符串),但检查网络选项卡下的chrome响应标签,我可以看到请求的响应是 0 $因此,为什么
xhr_test.responseText
无法显示相同的回复?
发送的调用是异步的(您已将'async'参数设置为true),这意味着您的警报正在立即发生,在请求结束之前。
您应该添加一个事件侦听器到 xhr.onreadystatechange
并使用该响应。
将'true'改为'false'会使这个简单的例子有效,但在一般情况下不是一个好主意。
关于 MDN页面Ajax 解释了如何使用XMLHttpRequest。
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?
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.
这篇关于XHR responseText是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!