我正在试图找出将后期数据发送到Django View函数的最佳方法.
我目前在我的jquery代码中有这样的东西:
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"); } });
数据在QueryDict对象中到达Django:
<QueryDict: {u'name': [u'Joe'],u'age': [u'20']}>
在view函数中,我可以访问如下值:
def do_something(request): if request.POST: name = request.POST.getlist('name')[0] age = request.POST.getlist('age')[0]
这种感觉错误(通过getlist访问post数据然后获取列表中的第一个元素)作为将post数据从jquery传递到django的方法.有更好的方式发送数据吗?
解决方法
这可能是做到这一点的“正确方法”,尽管它并不轻松.
您可以使用[]表示法从HttpRequest对象的POST列表中读取JSON数据,例如:
JSONdata = request.POST['data']
然后解码JSON数据:
dict = simplejson.JSONDecoder().decode( JSONdata )
并且您最终将所有JSON数据放在dict变量中.用法示例:
username = dict['name']