【问题标题】:How to receive ajax request using django?如何使用 django 接收 ajax 请求?
【发布时间】:2011-03-01 05:00:10
【问题描述】:

我的模板上有以下 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);}
          });
        }

我的 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

这次通话我错过了什么?

加特

【问题讨论】:

    标签: javascript jquery ajax django


    【解决方案1】:

    我认为问题在于序列化字典。当我测试您的代码时,我将其编辑为如下所示,并且可以正常工作:

    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 错误页面。

    【讨论】:

    • @jcady-“还要确保在 GET 查询字符串中传递了 title 的值。”这是什么意思?在被问到的问题中,这个人正在使用 POST!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多