传递值列表来Django的视图通过jQuery Ajax调用 [英] Passing list of values to django view via jQuery ajax call
问题描述
我想从一个网页传递数值(IDS)的列表,以另一种使用jQuery AJAX调用。我无法弄清楚如何传递和阅读列表中的所有值。我可以成功发布和读取1值,但不能多值。这是我到目前为止有:
I'm trying to pass a list of numeric values (ids) from one web page to another with jQuery ajax call. I can't figure out how to pass and read all the values in the list. I can successfully post and read 1 value but not multiple values. Here is what I have so far:
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 = '<p>This is not ajax</p>'
return HttpResponse(html)
使用萤火虫,我可以看到那个帖子包含的ID,很可能在错误的格式(terid = 1&安培; terid = 2)。所以我的看法的成分只摄取terid = 2。我究竟做错了什么?
With Firebug I can see that POST contains both ids but probably in the wrong format (terid=1&terid=2). So my ingredients view picks up only terid=2. What am I doing wrong?
编辑: 为了澄清,我需要的ourid变量传递值[1,2],在配料视图中的过滤器。
To clarify, I need the ourid variable pass values [1, 2] to the filter in the ingredients view.
推荐答案
我找到了一个解决方案,我原来的问题。在这里发布一个答案,希望这可以帮助别人。
I found a solution to my original problem. Posting it here as an answer, hopefully it helps somebody.
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 = '<p>This is not ajax</p>'
return HttpResponse(html)
这篇关于传递值列表来Django的视图通过jQuery Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!