2012-11-02 18 views
0

所以我有這樣的代碼:JSON序列化的Django和JSON解析jQuery的

def success_comment_post(request): 
    if "c" in request.GET: 
     c_id = request.GET["c"] 
     comment = Comment.objects.get(pk=c_id) 
     model = serializers.serialize("json", [comment]) 
     data = {'message': "Success message", 
       'message_type': 'success', 
       'comment': model } 
     response = JSONResponse(data, {}, 'application/json') 
     return response 
    else:   
     data = {'message': "An error occured while adding the comment.", 
       'message_type': 'alert-danger'} 
     response = JSONResponse(data, {}, 'application/json') 

和背部jQuery中我做了以下內容:

$.post($(this).attr('action'), $(this).serialize(), function(data) { 
    var comment = jQuery.parseJSON(data.comment)[0]; 
    addComment($("#comments"), comment); 

}) 

現在......在Django的功能,爲什麼我把評論中[] - > 模型= serializers.serialize( 「JSON」,[評論])

回到jQuery,爲什麼我必須要做jQuery.parseJSON(data.comment)[0]

無論如何,我不必這樣做?我覺得很奇怪,我必須硬編碼[0]

非常感謝!

+0

數據以數組形式出現,使用[0]確保您正在讀取數組的第一個元素 – 2012-11-02 12:26:30

+0

反正它不會出現數組?我真的只是傳遞一個對象。 – abisson

回答

0

那麼serializers.serialize只接受querysets或迭代器與django模型實例,但使用Comment.objects.get將返回一個對象,而不是一個迭代器,這就是爲什麼你需要把它放在[]使它成爲一個迭代器。

既然它是一個列表,你將不得不像JavaScript中的數組那樣訪問它。我建議不要使用序列化程序並使用simplejson將字段值轉換爲json。

示例代碼:

from django.utils import simplejson as json 
from django.forms.models import model_to_dict 

comment = Comment.objects.get(pk=c_id) 
data = {'message': "Success message", 
     'message_type': 'success', 
     'comment': model_to_dict(comment)} 
return HttpResponse(json.dumps(data), mimetype='application/json') 

我只提到你的代碼的相關部分。希望這可以解決你的問題