2010-06-08 144 views
5

我有我的模板,我想傳遞給我的Django的看法如下JQuery的Ajax請求,如何使用django接收ajax請求?

function loginUser(){ 
    $.ajax({ 
      type:"POST", 
      url :"/login-user/", 
      data:"title=ajax call", 
      datatype:"json", 
      error:function(data){alert('Error:'+data);} 
      success:function(data){alert('OK!'+data.message+','+data.code);} 
      }); 
     } 

我Django的看法是這樣的:

def login_user(request): 
    print "garbage" 
    print request.GET['title'] 
    return_dict = {'message': 'bla bla bla','code':324} 
    json=serialize("json",return_dict) 
    return HttpResponse(json, mimetype="application/x-javascript" 

當我打電話的AJAX功能,我得到以下錯誤:

錯誤:[對象的XMLHttpRequest]

和Django端我收到以下錯誤:

Traceback (most recent call last): 
    File "c:\python26\lib\site-packages\django\core\servers\basehttp.py", line 281, in run 
    self.finish_response() 
    File "c:\python26\lib\site-packages\django\core\servers\basehttp.py", line 321, in finish_response 
    self.write(data) 
    File "c:\python26\lib\site-packages\django\core\servers\basehttp.py", line 417, in write 
    self._write(data) 
    File "c:\python26\lib\socket.py", line 297, in write 
    self.flush() 
    File "c:\python26\lib\socket.py", line 284, in flush 
    self._sock.sendall(buffer) 
error: [Errno 10053] An established connection was aborted by the software in your host machine 

我在這次調用中錯過了什麼?

Gath

回答

6

我認爲問題在序列化字典。當我測試你的代碼,我編輯它看起來像這和它的工作:

from django.utils import simplejson 
def login_users(request): 
    print "garbage" 
    print request.GET['title'] 
    return_dict = {'message': 'bla bla bla','code':324} 
    json = simplejson.dumps(return_dict) 
    return HttpResponse(json, mimetype="application/x-javascript") 

另外,還要確保你傳遞一個值冠軍的GET查詢字符串。我也碰到過(可能需要檢查錯誤)。它有助於您使用像Firebug這樣的工具,甚至Webkit Inspector。這樣你可以查看Django從你的XHR請求返回的HTML錯誤頁面。

+0

很酷,它工作。謝謝。 – gath 2010-06-08 15:37:27

+0

@ jcady-「還要確保你在GET查詢字符串中傳遞了標題值。」這是什麼意思?在問題中問人使用POST! – David 2013-01-26 05:38:32

+0

非常非常感謝@jcady:D:D – 2013-12-19 14:18:45