問題描述
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 文件:
The main.py file:
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
顯示為頁面內容.
Now, when I hit upon the url localhost:8080/xhrtest
the browser promptly shows the response 0
as the page's content.
點擊url localhost:8080/xhr
間接點擊/xhrtest
,在alert框中彈出一個空字符串(responseText是一個空字符串)但是檢查在network標簽下chrome的response標簽,可以看到請求的響應是0
.
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
.
那么為什么 xhr_test.responseText
不能顯示相同的響應?
So why is xhr_test.responseText
not able to display the same response?
推薦答案
send 調用是異步的(您已將 'async' 參數設置為 true),這意味著您的警報會在請求完成之前立即發生.您應該向 xhr.onreadystatechange
添加一個事件偵聽器并在其中使用響應.
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.
將true"更改為false"可以使這個簡單的示例工作,但在一般情況下不是一個好主意.
Changing the 'true' to 'false' would make this simple example work, but is not a good idea in the general case.
Ajax 上的 MDN 頁面解釋了如何使用 XMLHttpRequest.
The MDN page on Ajax explains how XMLHttpRequest should be used.
這篇關于XHR responseText 是空字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!