How to get ajax request using django?

I have the following jQuery Ajax request on my template that I want to 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 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: [XMLHttpRequest object]

and on django side the following error occurs:

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 in this challenge?

Gough

+5
source share
1 answer

I think the problem is dictionary serialization. When I checked your code, I edited it to look like this:

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. , HTML, Django XHR.

+6

All Articles