开发者

How to receive ajax request using django?

I have the following JQuery Ajax request on my template that i want pass to my 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);}
          });
        }

my django view looks like this:

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"

When i call the ajax function i get the following error:

Error: [object XMLHttpRequest]

and on the django side i get the following error:

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

What am i missing on this call?

Gath


I think the problem is serializing the dictionary. When I tested your code, I edited it to look like this and it worked:

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")

Also make sure you are passing in a value for title in your GET query string. I ran into that as well (may need to be error checked). It helps if you use a tool like Firebug, or even the Webkit Inspector. That way you can view the HTML error pages that Django is returning from your XHR request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜