2013-10-23 1 views
3

html로 페이지입니다 :XHR에서 responseText는 빈 문자열을

<!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 안타 경고 상자에 빈 문자열을 팝업 URL localhost:8080/xhr

하지만 네트워크 탭에서 확인 크롬의 응답 탭합니다 (에서 responseText은 빈 문자열), I는 요청의 응답이 0 것을 볼 수 있습니다.

그렇다면 xhr_test.responseText은 왜 동일한 응답을 표시 할 수 없습니까?

+0

내 문제는 백엔드에서 gzip을 사용하지 않는 것이 문제였습니다. –

답변

5

보내기 요청은 비동기식입니다 ('async'매개 변수를 true로 설정 했음). 이는 요청이 완료되기 전에 즉시 경고가 발생하고 있음을 의미합니다. 이벤트 리스너를 xhr.onreadystatechange에 추가하고 그 안에 응답을 사용해야합니다.

'true'를 'false'로 변경하면이 간단한 예제가 작동하지만 일반적인 경우에는 좋지 않습니다.

MDN page on Ajax은 XMLHttpRequest를 사용해야하는 방법을 설명합니다.

+0

워! 고맙습니다. :) – tMJ