In the following code, there is a url which returns results in JSON format. I want to read the JSON and parse it in my code. However, when I run the code, the result is empty. Seems I can not send Cross Domain AJAX requests!
I also tried to include Access-Control-Allow-Credentials: true
in the code by writing xhrFields: { withCredentials: true }, crossDomain: true,
, but again it does not work. It gives the following error:
Error: jQuery111209679192922043036_1428845360268 was not called
$.ajax(
{
url:"http://ec.europa.eu/semantic_webgate/query/sparql?dataset=rasff&format=json&limit=10&query=select%20?p%20where%20+{+?s%20?p%20?o+}",
dataType:'jsonp',
type:"GET",
success:function(data)
{
alert("Data from Server"+JSON.stringify(data));
},
error:function(jqXHR,textStatus,errorThrown)
{
alert("You can not send Cross Domain AJAX requests : "+errorThrown);
}
});
How can I write a jsonp code to read this url ?
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"});
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
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).
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 . ");";
?>
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));
}
);