Search code examples
javascriptjqueryjsoncorsjsonp

How to retrieve data from JSON with javascript and jQuery?


Ok so I have been trying to retrieve a single string in JSON from this website: http://blog.teamtreehouse.com/api/get_recent_summary/?count=1

This is the snippet I have:

<html>
<head>
<title>Simple Page</title>
</head>
  <script src="jquery.js"></script>
    <script>
    $(document).ready(function() {
        $.getJSON('http://blog.teamtreehouse.com/api/get_recent_summary/?count=1', function(data) 
        { 
            alert(data.title)
        });     
    });
    </script>
</html>

Just trying to get a simple title and display it as an alert or just write it on the website, for some reason I can't get it right. I also checked that my jquery is working so it can't be that.

Thanks in advance!


Solution

  • No 'Access-Control-Allow-Origin' header is present on the requested resource.
    

    CORS HTTP header is missing, so you can't do AJAX requests directly. You need to use server side proxy or use http://crossorigin.me/ service to fetch data from remote website.

    Server you are accessing provides JSONP support, so you can convert it into JSONP call by adding callback=? to URL

    $.getJSON('http://blog.teamtreehouse.com/api/get_recent_summary/?count=1&callback=?', function(data) 
    { 
        alert(data.posts[0].title)
    });
    

    In case if JSONP is not supported you can use crossorigin.me service, but I would not rely on this service for production use.

    $.getJSON('http://crossorigin.me/http://blog.teamtreehouse.com/api/get_recent_summary/?count=1', function(data) 
            { 
                alert(data.posts[0].title)
            });