jqueryapidigg

Problem using $.getJSON() with jQuery


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.


Solution

  • 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.