我的应用程序的一部分接受了一些成分,然后吐出相关的食谱。我正在尝试将其转换为仅使用 AJAX。我在解析以 JSON 形式返回的数据并在前端访问它以供使用时遇到问题。
我在 Django views.py 中的代码如下所示:
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)
我的 javascript 看起来像这样:
//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); })
});
我以这种方式得到的输出最终为我提供了一个新的 li ,它似乎是 JSON 响应的每个字符......所以.each()
正在遍历每个字符。
我也尝试jQuery.parseJSON(data);
在运行每个之前使用,但这似乎只在只有一个 JSON 配方返回时才有效。我在想我在 JSON 中的格式不正确,或者我解析不正确?
提前致谢!