How to use jQuery and Django (ajax + HttpResponse)?

Suppose I have an AJAX function:

function callpage{ $.ajax({ method:"get", url:"/abc/", data:"x="+3 beforeSend:function() {}, success:function(html){ IF HTTPRESPONSE = "1" , ALERT SUCCESS! } }); return false; } } 

When my β€œview” is done in Django, I want to return HttpResponse('1') or '0' .

How do I know if this is successful and then make this warning?

+4
source share
2 answers

A typical workflow is for the server to return the JSON object as text and then interpret the object in javascript . In your case, you can return the text {"httpresponse": 1} from the server or use python json libary to create this for you.

JQuery has a nice json-reader (I just read the docs, so there might be errors in my examples)

JavaScript:

 $.getJSON("/abc/?x="+3, function(data){ if (data["HTTPRESPONSE"] == 1) { alert("success") } }); 

Django

 #you might need to easy_install this import json def your_view(request): # You can dump a lot of structured data into a json object, such as # lists and touples json_data = json.dumps({"HTTPRESPONSE":1}) # json data is just a JSON string now. return HttpResponse(json_data, mimetype="application/json") 

An alternative view suggested by Issy (cute, because he follows the DRY principle)

 def updates_after_t(request, id): response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(serializers.serialize("json", TSearch.objects.filter(pk__gt=id))) return response 
+16
source

Instead of doing all these messy, low-level ajax and JSON stuff, consider using the taconite plugin for jQuery. You just make a call to the backend, and you make the rest. It is well documented and easy to debug - especially if you use Firebug with FF.

+2
source

All Articles