3

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>
dda
  • 6,030
  • 2
  • 25
  • 34

2 Answers2

1

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.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
geniuscarrier
  • 4,199
  • 2
  • 21
  • 15
0

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

Community
  • 1
  • 1
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74