如何在Django中使用JQuery(ajax + HttpResponse)?
假设我有一个AJAX函数:
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'
。
我怎么知道这个操作是否成功,然后再弹出提示呢?
2 个回答
2
与其处理那些复杂的低级别的ajax和JSON的东西,不如考虑使用这个taconite插件来简化你的工作。你只需要向后台发出请求,剩下的事情它会帮你搞定。这个插件有详细的说明文档,而且调试起来也很简单——特别是如果你在用Firefox的Firebug工具。
16
一般的工作流程是让服务器返回一个JSON对象作为文本,然后在JavaScript中对这个对象进行解析。在你的情况下,你可以让服务器返回文本{"httpresponse":1},或者使用Python的json库来生成这个内容。
JQuery有一个很不错的JSON读取器(我刚看了文档,所以我的例子可能会有错误)
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原则)
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