3

I'm trying to run the following:

$.getJSON('http://services.digg.com/2.0/story.getTopNews?limit=25&callback=?', function(data) {
    console.log(data);
});

But I'm getting:

story.getTopNews:-1Resource interpreted as Script but transferred with MIME type application/json. story.getTopNews:2Uncaught SyntaxError: Unexpected token :

I've also tried something like this:

var url = "http://services.digg.com/2.0/story.getTopNews?limit=25";

$.ajax({
    url: url,
    crossDomain:true,
    dataType: "json",
    success:function(data,text,xhqr) {
        console.log(data);
    }
});

I get this:

XMLHttpRequest cannot load http://services.digg.com/2.0/story.getTopNews?limit=25. Origin http://sumews.com is not allowed by Access-Control-Allow-Origin. services.digg.com/2.0/story.getTopNews?limit=25GET http://services.digg.com/2.0/story.getTopNews?limit=25 undefined (undefined)

Any help would be greatly appreciated.

Cody.Stewart
  • 577
  • 4
  • 22

1 Answers1

4

Cross-domain AJAX requests are disallowed by the same-origin policy. This means that you can't do cross-domain requests in the normal way, and is the cause of the errors in your second example.

In the first example, you are trying the workaround -- JSONP. This works by putting a script element into the page that references the external script. The external script must respond by wrapping the data in a function call. If the external script does not support doing this (and it seems digg does not) than you cannot use the JSONP workaround.

Since the server sends JSON data (since it doesn't support JSONP), your browser gets confused when it tries to parse it as regular Javascript. This is the cause of your first errors.


It seems that digg does support JSONP, but it needs an extra argument type=javascript:

$.getJSON('http://services.digg.com/2.0/story.getTopNews?limit=25&type=javascript&callback=?', function(data) {
    console.log(data);
});

This works for me.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 1
    +1 What else could developers wish for? - Good questions, arising from real situations, and excellent answers like this one here. Add to that some trying on your own, wrestling with the issue, and you have the best learning experience free of charge, courtesy of SO and its excellent community. – Majid Fouladpour May 15 '11 at 21:47
  • I couldnt have said it better myself! Thanks for the help lonesomeday! – Cody.Stewart May 15 '11 at 22:19