我正在尝试使用 jQuery ajax 调用将数值 (ids) 列表从一个网页传递到另一个网页。我不知道如何传递和读取列表中的所有值。我可以成功发布和读取 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);
}
});
});
/成分/ View :
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 = '<p>This is not ajax</p>'
return HttpResponse(html)
使用 Firebug,我可以看到 POST 包含两个 id,但可能格式错误(terid=1&terid=2)。所以我的成分 View 只显示 terid=2。我做错了什么?
编辑: 为了澄清,我需要 ourid 变量将值 [1, 2] 传递到成分 View 中的过滤器。
最佳答案
您可以在 View 中通过request.POST.getlist('terid[]')访问该数组
在 JavaScript 中:
$.post(postUrl, {terid: values}, function(response){
alert(response);
});
在view.py中:
request.POST.getlist('terid[]')
它非常适合我。
关于jquery - 通过 jQuery ajax 调用将值列表传递给 django View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11176594/