Apopei Andrei Ionut
Apopei Andrei Ionut

Reputation: 451

Get JSON data and put it into HTML tag

I'm trying to solve a issue regarding to JSON data (getting and post it). Bellow I posted my code which doesn't work and I don't know why? I checked with Firebug and says that it's ok: 200 OK sourceforge.net 1.4 KB 216.34.181.60:80

What I'm trying to do, is to get some stats from a sourceforge project and put it into a div tag.

The link is a valid json (http://sourceforge.net/projects/rdss/files/stats/json?start_date=2010-12-01&end_date=2012-11-24).

<html>
  <head>...</head>
  <body>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $(document).ready(function() {
          $.getJSON("http://sourceforge.net/projects/rdss/files/stats/json?start_date=2010-12-01&end_date=2012-11-24", function(data) {
            $.each(data.posts, function(i,data) {
              var div_data = "<div>"+data.oses+"</div>";
              $(div_data).appendTo("#testjson");
            });
          });
          return false;
        });
      });
    </script>
    <div id="testjson"></div>
  </body>
</html>

Upvotes: 3

Views: 1839

Answers (2)

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

You are trying to do a cross-browser request: http://en.wikipedia.org/wiki/Same-origin_policy.

So, getJSON is failing and trowing exception.. see "No 'Access-Control-Allow-Origin' header is present on the requested resource"

When this happens you can workaround using CORS.

But for this workaround work, you need server be CORS-enabled, what unfortunately sourceforge isn't.

You can see this by checking response header. It has the key Access-Control-Allow-Origin:*.

Usually, you can do this by accessing Developer Tools in Browsers:
- Select Network tab.
- Identify JSON page and select.
- Open Header tab
- Go to Response Headers section.

See an example:

enter image description here

Upvotes: 0

geniuscarrier
geniuscarrier

Reputation: 4239

This is a cross domain issue. Check the console. You need write a proxy at the server side to get around. Based on your server side language, you can Google a proxy snippet.

Upvotes: 1

Related Questions