通过jQuery ajax调用将值列表传递给django视图
我试图通过jQuery ajax调用将一个数值(ID)列表从一个网页传递到另一个网页。 我无法弄清楚如何传递和读取列表中的所有值。 我可以成功发布和读取1个值但不能读取多个值。 这是我到目前为止:
jQuery的:
var postUrl = "http://localhost:8000/ingredients/"; $('li').click(function(){ values = [1, 2]; $.ajax({ url: postUrl, type: 'POST', data: {'terid': values}, traditional: true, dataType: 'html', success: function(result){ $('#ingredients').append(result); } }); });
/成分/查看:
def ingredients(request): if request.is_ajax(): ourid = request.POST.get('terid', False) ingredients = Ingredience.objects.filter(food__id__in=ourid) t = get_template('ingredients.html') html = t.render(Context({'ingredients': ingredients,})) return HttpResponse(html) else: html = 'This is not ajax
' return HttpResponse(html)
使用Firebug,我可以看到POST包含两个ID,但可能格式错误(terid = 1&terid = 2)。 所以我的成分视图只选择了terid = 2。 我究竟做错了什么?
编辑:为了澄清,我需要myid变量传递值[1,2]到成分视图中的filter。
您可以通过视图中的request.POST.getlist(’terid []’)访问此数组
在javascript中:
$.post(postUrl, {terid: values}, function(response){ alert(response); });
在view.py中:
request.POST.getlist('terid[]')
它对我来说很完美。
我找到了原始问题的解决方案。 在这里发布它作为答案,希望它有助于某人。
jQuery的:
var postUrl = "http://localhost:8000/ingredients/"; $('li').click(function(){ values = [1, 2]; var jsonText = JSON.stringify(values); $.ajax({ url: postUrl, type: 'POST', data: jsonText, traditional: true, dataType: 'html', success: function(result){ $('#ingredients').append(result); } }); });
/成分/查看:
def ingredients(request): if request.is_ajax(): ourid = json.loads(request.raw_post_data) ingredients = Ingredience.objects.filter(food__id__in=ourid) t = get_template('ingredients.html') html = t.render(Context({'ingredients': ingredients,})) return HttpResponse(html) else: html = 'This is not ajax
' return HttpResponse(html)
这部分是你的问题:
ourid = request.POST.get('terid', False) ingredients = Ingredience.objects.filter(food__id__in=ourid)
您需要反序列化JSON字符串。
import json ourid = json.loads(request.POST.get('terid'))
看来你在这里将数组设置为字符串
data: {'terid': values},
它应该是
data: {terid: values}
尝试发送这样的数据:
data: values;