metrampaz
metrampaz

Reputation: 663

getJSON + reddit api — how to bite it?

I would like to append my div with first permalink from subreddit. I've tried following jQuery's documentation, Smashing Magazine's article and reddit's github but without any effect. Please help me understand how to do this.

Jquery:

$(document).ready(function(){
        $.getJSON("api.reddit.com/r/aww/.json", function(json){
           $(".slodziaki").append("<p>Permalink</p>"+ json.data.children.data[0].permalink)'         
        });
});

HTML:

<html>
    <head>
        <meta charset="utf-8">
        <title>Słodziaki.</title>
        <script>

        </script>
    </head>
    <body>
        <div class="slodziaki">
            Reddit api test.
        </div>
    </body>
</html>

jsFiddle: http://jsfiddle.net/AdVS3/2/

Upvotes: 1

Views: 1401

Answers (1)

Nic
Nic

Reputation: 13733

You've got the right idea, but most browsers won't allow you to access api.reddit.com because of XSS protection and the Same Origin Policy. Another option is to use cURL or similar via your server side script to pull in the JSON, and jQuery would access that resource from the local server. If you provide your scripting language, I can help even further.

Luckily, this is pretty easy with PHP. You've got quite a few options, but I'd suggest starting with file_get_contents() from that page. If you're looking for a performance increase, you should explore the cURL options also noted there. Fairly straight forward, all it does is go out to the specified URL (api.reddit.com/r/aww/.json) and displays it locally.

If you were to put that into a file called aww.php, then you would just call aww.php in your .getJSON function.

Upvotes: 2

Related Questions