我的模板上有以下 JQuery Ajax 请求,我想将其传递给我的 Django View ,
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 View 如下所示:
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
我在这个电话中错过了什么?
加思
最佳答案
我认为问题在于字典的序列化。当我测试您的代码时,我将其编辑为如下所示并且有效:
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 查询字符串中传递了 title 的值。我也遇到过(可能需要进行错误检查)。如果您使用像 Firebug 这样的工具,甚至是 Webkit Inspector,它会有所帮助。这样您就可以查看 Django 从您的 XHR 请求返回的 HTML 错误页面。
关于javascript - 如何使用 Django 接收 ajax 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2998275/