Search code examples
javascriptjqueryjsonwordpressmustache

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. 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. Could it be because I'm trying to parse data from another domain?

My code looks like this:

HTML:

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

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.


Solution

  • 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).

    This is as simple as using the exact code you have, but changing the url into:

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