응용 프로그램의 일부가 몇 가지 재료를 사용하여 관련 조리법을 뱉어냅니다. 나는 AJAX 만 사용하도록 변환하려고합니다. JSON으로 돌아와서 프런트 엔드에서 사용하기 위해 액세스하는 데이터를 파싱하는 데 문제가 있습니다.Django 백엔드에서 jQuery를 통해 반환 된 JSON 객체의 포장 풀기 및 표시
장고 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)
:
이//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); })
});
나는이 방법을지고있어 출력은 저를 포기 끝 JSON 응답의 각 문자 인 것처럼 보이는 새로운 li ... .each()
이 각 문자를 통과합니다.
또한 각각을 실행하기 전에 jQuery.parseJSON(data);
을 사용해 보았습니다.하지만이 방법은 하나의 JSON 래서 피만 반환 될 때만 작동하는 것으로 보입니다. 내가 JSON 형식이 잘못되었거나 잘못 파싱한다고 생각하고 있습니까?
미리 감사드립니다.