3

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をページのコンテンツとしてすぐに表示します。

localhost:8080/xhr間接的にヒットする urlをヒット/xhrtestすると、アラート ボックスに空の文字列がポップアップ表示されます (responseText は空の文字列です) 0

では、なぜxhr_test.responseText同じ応答を表示できないのでしょうか。

4

1 に答える 1

7

send の呼び出しは非同期です (「async」パラメーターを true に設定しました)。これは、要求が完了する前にアラートがすぐに発生することを意味します。イベントリスナーを追加して、xhr.onreadystatechangeその中で応答を使用する必要があります。

「true」を「false」に変更すると、この単純な例が機能しますが、一般的なケースではお勧めできません。

AjaxのMDN ページでは、XMLHttpRequest の使用方法について説明しています。

于 2013-10-23T18:37:52.173 に答える