简体   繁体   中英

Can't access another domain's valid json with jquery and ajax

I'm trying to access a JSON api of a certain adult-oriented website, but I can't get it to work. Here's the jsfiddle: http://jsfiddle.net/SSqwd/ and here is the code:

$.ajax({url: 'http://api.redtube.com/?data=redtube.Videos.searchVideos&search=sex&thumbsize=big&page=1&output=json&callback=?',
    dataType: 'json',
    success: function(data) {
        console.log(data);
    }
});

I get

Uncaught SyntaxError: Unexpected token :

even though when I browse to the page myself and check the json on jsonlint, it is perfectly valid.

What's going wrong here?

Since you specified a cross domain request jQuery will by default attempt to request that URL using JSONP even though you've only set the dataType to JSON. So what actually happens is the following script tag is added to the DOM:

<script src="http://api.redtube.com/?data=redtube.Videos.searchVideos&search=sex&thumbsize=big&page=1&output=json&callback=?" type="text/javascript"></script>

(the ? actually gets replaced with a function name jQuery generates)

Your browser then tries to execute the returned data. However, as it is not actually JSONP and is just pure JSON what it returns is invalid javascript and hence you get the Syntax error.

You can reproduce the same error by just using:

<script src="http://api.redtube.com/?data=redtube.Videos.searchVideos&search=sex&thumbsize=big&page=1&output=json&callback=?" type="text/javascript"></script>

And doing nothing else. Or you can copy and paste the response from that URL and wrap it in script tags, you'll get the same error thrown.

The only way to solve this error is use an API that supports JSONP or implement a sort of proxy that requests the data via your own server on the same domain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM