Jquery Ajax发布到Django View [英] Jquery Ajax Post to Django View
问题描述
我试图找出发送数据到Django View功能的最佳方式。
I'm trying to figure out the best way to send post data to a Django View function.
我目前在我的jquery代码中是这样的:
What I have currently in my jquery code is something like this:
var name = 'Joe';
var age = 20;
$.ajax({
url:"/do_something/",
type: "POST",
data: {name: name, age: age},
success:function(response){},
complete:function(){},
error:function (xhr, textStatus, thrownError){
alert("error doing something");
}
});
数据到达Django中的QueryDict对象:
The data arrives in Django in a QueryDict object:
<QueryDict: {u'name': [u'Joe'], u'age': [u'20']}>
在视图函数中,我可以访问这样的值:
In the view function, I can access the values like this:
def do_something(request):
if request.POST:
name = request.POST.getlist('name')[0]
age = request.POST.getlist('age')[0]
这感觉不知何故(通过获取列表访问帖子数据,然后获取列表中的第一个元素)作为将数据从jquery传递到django的一种方式。有没有更好的方式发送数据?
This feels wrong somehow (accessing the post data through a getlist and then getting the first element in the list) as a way to pass post data from jquery to django. Is there a better way to send data?
推荐答案
这可能是正确的方法,虽然不是任何打火机。
This might be the "right way" to do this, though it is not any lighter.
您可以使用[]符号从HttpRequest对象的POST列表中读取JSON数据,例如:
You can read the JSON data from HttpRequest object's POST list using [] notation, for example:
JSONdata = request.POST['data']
然后解码JSON数据:
and then decode the JSON data:
dict = simplejson.JSONDecoder().decode( JSONdata )
并且最终将所有的JSON数据都添加到dict变量中。示例用法:
and you end up having all your JSON data in the dict variable. Example usage:
username = dict['name']
这篇关于Jquery Ajax发布到Django View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!