How should I approach this if the server doesn't respond with JSONP? I've tried several options with $.ajax, but can't get it to work.
//var url = 'https://coinbase.com/api/v1/currencies/exchange_rates';
var url = 'http://blockchain.info/ticker';
$.ajax({
type: 'GET',
url: url,
//jsonpCallback: 'jsonCallback',
contentType: 'application/json',
//async: false,
//dataType: 'jsonp',
//xhrFields: {
// for CORS?
// withCredentials: false
//},
success: function (json) {
debugger;
},
error: function (json) {
debugger;
}
});
$.ajax({
url: "http://yoururl",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status) {
alert("error");
}
});
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
Essentially you have to change the response headers on the server side.
It sounds like you're doing a cross-domain request to a server that doesn't support JSONP.
There's a good reason why browsers refuse data from servers that don't want their data to be used in cross-domain requests. If browsers didn't do that, there's be a ton of security problems all over the web. So the server needs to allow this for this to work.
There are basically two ways a server can allow this: the old ugly way through JSONP, but you say it doesn't support that. Though you could still try by changing your url to 'http://blockchain.info/ticker?callback=?'
and datatype to jsonp.
But there's also the new, clean way with CORS headers. If the server adds a Accept-Control-Allow-Origin: *
header to its response, anyone (using a modern browser) can use the data with a normal Ajax call.
If the server doesn't allow you to use its data, you're out of luck.
It looks like you're trying to send an AJAX request to blockchain.info and retrieve the JSON feed. Luckily they've added support for CORS.
Simply pass the parameter cors=true
to the requested url (ex. http://blockchain.info/ticker?cors=true
) and you should be able to grab the data.
Looks like CORS are only supported for a few API calls as per https://blockchain.info/api/blockchain_api.