0

我在使用Django的python中有一個GAE應用程序。我試圖使用jquery的get/getJSON api從python api獲取json,但它不會將讀取的字符串讀爲json。我在這裏錯過了什麼嗎?getJSON不檢索json對象

Django的模板

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" > </script> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
    $.get('/test/api?request=getallwords', function(json) { 
     $('body').append(json); 
     var j = JSON.stringify(json) 
     $.each(json.details,function(i){ 
      $('#list').append($('<li>' + this.word + '</li>')); 
     }); 
     alert(j); 
    }); 
    },'json'); 
</script> 
</head> 
<body> 
<ol id="list"> 
</ol> 

而這裏的蟒蛇API。

words = Word.all().fetch(20) 
for w in words: 
    d = {"word":w.name.encode('utf-8'),"lists":[]} 
    for l in w.word_lists: 
     d["lists"].append({"list":l.word_list.name.encode('utf-8')}) 
success["details"].append(d) 
self.response.headers['Content-Type'] = 'application/javascript' 
self.response.out.write(success) 

並且json例子

{ '響應': '成功', '細節':[{ '字': 'mcity', '名單':[{ '清單': 'infy'},{'list':'dasd'}]},{'word':'mcity_1','lists':[]},{'word':'mcity_2','lists':[]} ,{'word':'mydc','lists':[{'list':'infy'}]},{'word':'hyddc','lists':[{'list':'infy'} ]},{'word':'abysmal','lists':[{'list':'gre words'}]},{'word':'ascent','lists':[{'list':' gre'words'},{'list':'infy'},{'list':'mine'}]},{'word':'assda','lists':[{'list':'dasd'} ]}]}

回答

0
$(document).ready(function(){ 
    $.get('/test/api?request=getallwords', function(json) { 
     $('body').append(json); 
     var j = JSON.stringify(json) 
     $.each(json.details,function(i){ 
      $('#list').append($('<li>' + this.word + '</li>')); 
     }); 
     alert(j); 
    }); // error, you close the $('document').ready() here 
    },'json'); 

將關閉想以下幾點:

$(document).ready(function(){ 
    $.get('/test/api?request=getallwords', function(json) { 
     $('body').append(json); 
     var j = JSON.stringify(json) 
     $.each(json.details,function(i){ 
      $('#list').append($('<li>' + this.word + '</li>')); 
     }); 
     alert(j); 
    },'json'); 
}); 
+0

這實際上是問題之一。我意外地除去'self.response.headers [「內容 - 類型」] =「應用/ javascript''也改變'self.response.out.write(成功)''self.response.out.write(js on.dumps(成功))',我得到它顯示。謝謝您的幫助! – adifire

0

看起來像你正在使用jQuery get()不是getJSON(),所以你需要在請求對象中具體的dataType作爲JSON。

如果你想在「json的」下方是這樣做的,我想你已經得到了閉括號混合起來(GET前$(document).ready()

}); 
    },'json');