fin*_*pin 13 django ajax jquery
我正在尝试使用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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
/成分/查看:
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)
Run Code Online (Sandbox Code Playgroud)
使用Firebug,我可以看到POST包含两个ID,但可能格式错误(terid = 1&terid = 2).所以我的成分视图只选择了terid = 2.我究竟做错了什么?
编辑: 为了澄清,我需要myid变量传递值[1,2]到成分视图中的过滤器.
小智 36
您可以通过视图中的request.POST.getlist('terid []')访问此数组
在javascript中:
$.post(postUrl, {terid: values}, function(response){
alert(response);
});
Run Code Online (Sandbox Code Playgroud)
在view.py中:
request.POST.getlist('terid[]')
Run Code Online (Sandbox Code Playgroud)
它对我来说很完美.
我找到了解决我原来问题的方法。将其发布在这里作为答案,希望它可以帮助某人。
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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
/成分/视图:
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 = '<p>This is not ajax</p>'
return HttpResponse(html)
Run Code Online (Sandbox Code Playgroud)