For JSONP, set your dataType:'json'
to dataType:'jsonp'
. Also, your sever needs to know about JSONP. A true JSONP-aware web service will read in the mandatory ?callback=?
parameter of your URL.
Here is what a proper JSONP response looks like: http://ip.jsontest.com/?callback=methodName with response:
methodName({"ip": "151.194.190.31"});
Solution 1 - JSONP with callback
Find out if that URL supports JSONP and a callback name. If so, use a callback parameter and use JSONP. No CORS problem. Here is a sample Fiddle.
More info: jquery + jsonp return syntax error even when the response is json
Solution 2 - Permit CORS and use plain JSON
Add the Access-Control-Allow-Origin: *
to the response from that URL (if you can control it), and process it as a JSON response (not JSONP).
Solution 3 - DIY JSONP wrapper
If that URL doesn't support JSONP, and it doesn't allow CORS, then you can cheat by using some server-side code to scrape the JSON results of that URL, then wrap the JSON in a callback function, set the header to Access-Control-Allow-Origin: *
, and return the results to your AJAX JSONP script. Pretty neat, huh?
Oh, and here you go:
<?php
// xss-service.php - Bare-bones demo by @Drakes
$callback = isset($_GET["callback"]) ? $_GET["callback"] : "?";
$json = file_get_contents('http://ec.europa.eu/semantic_webgate/query/sparql?dataset=rasff&format=json&limit=10&query=select%20?p%20where%20%20%7B%20?s%20?p%20?o%20%7D');
header('Access-Control-Allow-Origin: *');
header("Content-type: application/json");
echo $callback . "(" . $json . ");";
?>
Solution 4 - JSONP Proxy service
If you just need to get this working now, you can use an online JSONP proxy service, for example, Yahoo's YQL service. Then, using your URL with no JSONP, and no CORS, you can do:
var theUrl = "http://ec.europa.eu/semantic_webgate/query/sparql?dataset=rasff&format=json&limit=10&query=select%20?p%20where%20%20%7B%20?s%20?p%20?o%20%7D";
var yql = 'http://query.yahooapis.com/v1/public/yql?'
+ 'q=' + encodeURIComponent('select * from json where url=@url')
+ '&url=' + encodeURIComponent(theUrl)
+ '&format=json&callback=?';
$.getJSON(yql,
function (data) {
alert(JSON.stringify(data));
}
);
Demo: http://jsfiddle.net/L4foze7t/