简体   繁体   English

无法使用jQuery从Wordpress JSON API解析JSON数据

[英]Can't parse JSON data from Wordpress JSON api using jQuery

I'm trying to create a simple posts feed from a Wordpress website using the JSON API plugin and while the JSON url returns data it does nothing when I attempt to parse the url using jquery. 我正在尝试使用JSON API插件从Wordpress网站创建一个简单的帖子供稿,并且当JSON url返回数据时,当我尝试使用jquery解析url时它什么也没做。 When I copy the data into a JSON file and use it in my Mustache template it works so I know the fault is not with the template. 当我将数据复制到JSON文件并在我的Mustache模板中使用它时,它可以工作,因此我知道问题不在模板上。 Could it be because I'm trying to parse data from another domain? 可能是因为我试图解析另一个域中的数据?

My code looks like this: 我的代码如下所示:

HTML: HTML:

<div id="posts"></div>

Javascript: Javascript:

<script id="posts-list" type="text/template">
    {{#posts}}
        <div class="item">
            <img src="{{thumbnail}}" alt="{{title}}">
            <h3>{{title}}</h3>
            {{{excerpt}}}
            <span><a href="{{url}}">read more</a></span>
        </div>
    {{/posts}}
</script>

<script src="//code.jquery.com/jquery.js" type="application/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.min.js" type="application/javascript"></script>
<script>
    $(function(){
        $.getJSON("http://wetu.co.zw/newsapp/?json=get_recent_posts&count=10", function(data){
            var template = $('#posts-list').html();
            var html = Mustache.to_html(template, data);
            $('#posts').html(html);
            });
        });
</script>

Please help and thank you. 请帮助,谢谢。

Because this is an x-domain request and you don't have access to the server settings, you can instruct jquery to do a JSONP request (that wordpress json api also supports). 由于这是x域请求,并且您无权访问服务器设置,因此可以指示jquery进行JSONP请求(wordpress json api也支持该请求)。

This is as simple as using the exact code you have, but changing the url into: 这就像使用您拥有的确切代码一样简单,但是将url更改为:

http://wetu.co.zw/newsapp/?json=get_recent_posts&count=10&callback=?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM