2013-06-27 67 views
2

我有一個視圖頁面,目前有兩列數據顯示,很快將擴展到四個。每列包含該特定模型的QuerySet的結果。在Django的Simplejson返回JSON.parse錯誤

下面是我在我的views.py方法:

if request.REQUEST["type"] == "text": 
     client = Client.objects.get(client_name = request.REQUEST["search"]) 
     peerList = ClientPeers.objects.prefetch_related().filter(client = client.client) 
     compList = ClientCompetitors.objects.prefetch_related().filter(client = client.client) 

else: 
    peerList = ClientPeers.objects.prefetch_related().filter(client = request.REQUEST["search"]) 
    compList = ClientCompetitors.objects.prefetch_related().filter(client = request.REQUEST["search"]) 

for peer in peerList: 
    peerlst.append({"pid" : peer.parentorg.parentorg, "pname" : peer.parentorg.parentorgname}) 

for comp in compList: 
    complst.append({"cid" : comp.parentorg.parentorg, "cname" : comp.parentorg.parentorgname}) 

lst.append(simplejson.dumps(peerlst)) 
lst.append(simplejson.dumps(complst)) 

return HttpResponse(simplejson.dumps(lst), mimetype = "text/json") 

這使我的數據的二維數組發送到瀏覽器的格式

[ { //JSON }, { //JSON } ] 

在我jQuery.ajax成功功能,我有

function handler(results) { 
    var data = JSON.parse(results); 

    for (var i = 0; i < data[0].length; i++) 
    $("#available_peers").append("<li>" + data[0][i].pname + "</li>"); 

    for (var i = 0; i < data[1].length; i++) 
    $("#available_competitors").append("<li>" + data[1][i].cname + "</li>"); 

firebug顯示GET請求的作品,我可以看到數據在th e響應選項卡。但是,如果我有

var peers = JSON.parse(data[0]); 
var comps = JSON.parse(data[1]); 

更換var data = JSON.parse(results)爲什麼一個方法的工作,但另一個不控制檯打印出

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data 
var data = JSON.parse(results) 

這個錯誤會消失?

+0

請嘗試更改應用程序/ JSON文本/ JSON –

+0

什麼全'。阿賈克斯()'調用看起來像? –

+0

json數據的外觀如何? –

回答

1

調用jQuery ajax()將對返回的數據類型進行智能猜測。在你的例子中,function handler(results)results變量將已經是解碼的JSON對象,其中包含數組中的兩個項目。 JSON.parse(data[0])的工作原理是,您已將JSON編碼的數據作爲字符串返回。

輸出數組中放置之前,不要編碼單獨列表元素JSON:

lst.append(peerlst) # <-- Don't encode to JSON string here 
lst.append(complst) 

return HttpResponse(simplejson.dumps(lst), mimetype = "application/json") # <-- Single JSON encoding