2010-11-12 157 views
0

奇怪 - 我似乎無法使用jQuery.get()從django.HttpResponse讀取響應。jQuery.get()沒有得到從Django HTTP響應

從Django的結束,我有一個觀點:

def hello(request): 
    return HttpResponse("Hello world", content_type="application/html") 

和網址:

urlpatterns = patterns('', 
    ('^hello/$', hello), 

當我訪問http://localhost:8000/hello/,我看到 「Hello World」 作爲預期。

在我的網頁上,不過,我這樣做:

<html><head> 
<script src="/asgapp/lib/jquery/jquery-1.4.3.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
     $('#testdiv').html("initial"); 
     $.get('http://localhost:8000/hello/', function(data){ 
     if(data){ 
      $('#testdiv').html(data); 
     } 
     else{ 
      $('#testdiv').html("no data"); 
     }}); 
    }); 
</script> 
</head> 
<body> 
    <h1>test page</h1> 
    <div id="testdiv">(empty)</div> 
</body> 
</html> 

在Firebug,我看到了請求,但響應是空的,即使Django的已經看到了請求和處理響應。

我錯過了什麼嗎?這是一個jQuery問題或django.HttpResponse的事情?

回答

2

您不能向這樣的其他域請求(不同的端口屬於此),它被same origin policy阻止。這不是jQuery或Django的事情,它是瀏覽器如何實現XmlHttpRequest對象的安全性。

要向另一個域發出請求,您需要使用JSONP來提取數據。

+0

謝謝 - 我沒有意識到一個端口算作一個不同的域! – 2010-11-13 18:24:15