如何使用JQuery和Django(ajax + HttpResponse)? [英] How to use JQuery and Django (ajax + HttpResponse)?
问题描述
假设我具有AJAX功能:
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;
}
}
当我的视图"在Django中执行时,我想返回HttpResponse('1')
或'0'
.
When my "View" executes in Django, I want to return HttpResponse('1')
or '0'
.
我怎么知道它是否成功,然后发出警报?
How can I know if it was successful, and then make that alert?
推荐答案
The typical workflow is to have the server return a JSON object as text, and then interpret that object in the javascript. In your case you could return the text {"httpresponse":1} from the server, or use the python json libary to generate that for you.
JQuery有一个不错的json-reader(我只是阅读了文档,所以示例中可能有错误)
JQuery has a nice json-reader (I just read the docs, so there might be mistakes in my examples)
JavaScript:
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")
Issy建议使用另一种视图(之所以可爱,是因为它遵循DRY原理)
An alternative View suggested by Issy (cute because it 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
这篇关于如何使用JQuery和Django(ajax + HttpResponse)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!