我正在对服务器进行 ajax 调用,并希望接收一个数组以进行进一步处理。我是一个初学者,对我真正在做什么感到很困惑。下面是我到目前为止想出的一个片段。在我尝试处理返回的数据之前,它运行良好。我认为我的问题是我并不真正了解如何形成正确的响应以及如何处理它。
JAVASCRIPT/JQUERY:
var shoppingList = {
// SOME CODE BEFORE
'foodIngredients' : function() {
// Send a list of food ids and receive an array of necessary ingredients. Make the returned array unique.
$.ajax({
url: 'http://localhost:8000/ingredients/',
// ingredients.html template:
// [{% for item in ingredients %}{% if forloop.last %}{{ item.id }}{% else %}{{ item.id }},{% endif %}{% endfor %}]
type: 'POST',
data: JSON.stringify(shoppingList.selectedFoods),
dataType: 'text',
cache: 'false',
success: function(result){
console.log(result); // [33,85,88,89,91]
shoppingList.returnedIngredients = result;
shoppingList.uniqueIngredients = _.unique(shoppingList.returnedIngredients);
console.log(shoppingList.uniqueIngredients); // [,3,,,8,5,9,1,] <-- NOT OK; Expected [33,85,88,89,91]
}
});
},
// SOME CODE AFTER
};
成分视图:
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)