Reputation: 4071
I'm making an ajax call to the server and want to receive an array for further processing. I'm a beginner and quite confused about what I'm really doing. Below is a snippet that I came up with so far. It works well until I try to process the returned data. I think my problem is that I don't really understand how to form a correct response and how to process it.
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
};
INGREDIENTS VIEW:
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)
Upvotes: 0
Views: 795
Reputation: 782653
result is a string, not an array of numbers. So _.unique is returning the unique characters in the string. You need to use jSON.Parse
to translate the result to an array. Or specify dataType: 'json'
in the options.
Upvotes: 1