Reputation: 1600
I have code like this:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
var ex_rate = data["market_price_usd"];
document.getElementById('btcusd777').innerHTML = ex_rate;
}
};
xhr.open('GET', 'https://blockchain.info/ru/stats?format=json');//&cors=true doesn't help
xhr.send();
</script>
1 BTC = <span id="btcusd777"></span> USD
But it doesn't work because api is on different domain. Is there a way to fix it somehow? I don't want to use jquery
Upvotes: 0
Views: 107
Reputation: 25634
The docs state that "Some API calls are available with CORS headers if you add a cors=true parameter to the request." But that does not seem to be the case for the call you made.
There seems to be another call that allows cross origin requests:
https://blockchain.info/ru/q/24hrprice
So just adjust your call like this:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('btcusd777').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'https://blockchain.info/ru/q/24hrprice');
xhr.send();
1 BTC = <span id="btcusd777"></span> USD
Upvotes: 1
Reputation: 1034
It doesn't seem to support CORS, so if you don't have control over the API development, that I guess it's the case, the only way to do it is by proxying it through your own web server.
If you have an nginx: https://www.nginx.com/resources/admin-guide/reverse-proxy/
If you are on apache: http://httpd.apache.org/docs/2.2/mod/mod_proxy.html
Note that jquery or any other javascript framework will not help with this as it's a browser restriction. It doesn't seem to have crossdomain.xml file so flash will not help either.
Upvotes: 0