如何使用django接收ajax请求?

gat*_*ath 5 javascript django ajax jquery

我的模板上有以下JQuery Ajax请求,我希望传递给我的django视图,

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);}
          });
        }
Run Code Online (Sandbox Code Playgroud)

我的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"
Run Code Online (Sandbox Code Playgroud)

当我调用ajax函数时,我收到以下错误:

错误:[object 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
Run Code Online (Sandbox Code Playgroud)

我在这次电话会议中缺少什么?

迦特

jca*_*ady 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")
Run Code Online (Sandbox Code Playgroud)

还要确保在GET查询字符串中传递title的值.我也碰到了(可能需要进行错误检查).如果您使用Firebug之类的工具,甚至是Webkit Inspector,它会有所帮助.这样您就可以查看Django从XHR请求返回的HTML错误页面.