A part of my application takes in some ingredients then spits back relevant re开发者_开发知识库cipes. I am trying to convert it to use only AJAX. I'm running into problems parsing the data coming back in JSON and accessing it for use on the front end.
My code in the Django views.py looks like this:
recipes = Recipe.objects.all() #shortened to all objects for example purposes
import simplejson
data = ''
for r in recipes:
the_date = r.date_created.strftime("%b %d")
recipe_dict = { 'id' : r.id,
'name' : r.name,
'user' : r.user.username,
'date_created' : the_date,
'votes' : r.votes,
'slug' : r.slug }
data += simplejson.dumps(recipe_dict)+'\n'
return HttpResponse(data)
My javascript looks like this:
//request an updated list of recipes with AJAX
$.get('/recipes/discover', { 'ingredients': ingredients },
//display these new relevant recipes
function(recipes){
$.each(recipes, function() {
$("#results").append("<li id='recipe-"+ this.id +"'>"+ this.name +"</li>");
})
})
.complete(function(){ $('#loading_spinner').fadeOut(1000); })
});
The output I've been getting with this way ends up giving me a new li for what appears to be each character of the JSON response... so .each()
is going through each character.
I also tried using jQuery.parseJSON(data);
before running each, but this only seems to work when there is only one JSON recipe returned. I am thinking I have something formatted incorrectly in the JSON, or I'm parsing it incorrectly?
Thanks in advance!
You need to separate objects in JSON with a comma, and enclose arrays within [].
It looks like your returned JSON would look something like:
{'name': ... }{'name':...}
And it should look like:
[{'name': ... },{'name':...}]
That's why a single recipe would parse correctly since it's a valid JSON object, but multiples don't work.
If it is valid JSON, jQuery.parseJSON(...) will work correctly.
Here is a JSON Reference.
精彩评论