簡體   English   中英

getJSON沒有檢索json對象

[英]getJSON is not retrieving json object

我使用Django在python中有一個GAE應用程序。 我正在嘗試使用jquery的get / getJSON API從python API獲取json,但它不會將傳遞的字符串讀取為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>

這是python 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的例子

{'response':'success','details':[{'word':'mcity','lists':[{'list':'infy'},{'list':'dasd'}]}, {'word':'mcity_1','列表':[]},{'word':'mcity_2','列表':[]},{'word':'mydc','列表':[{' 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'}]}]}}

看起來您正在使用jQuery get ()而不是getJSON()因此您需要在請求對象中將dataType特定為JSON。

如果您認為下面的'json'正在執行此操作,則我認為您混淆了結束符(GET將在$(document).ready()之前關閉。

});
    },'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);
    }); // 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');
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM