正在从 api 加载数据到 javascript
Loading data from api in javascript
我有这样的代码:
<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
但它不起作用,因为 api 在不同的域中。有没有办法以某种方式修复它?我不想使用 jquery
它似乎不支持 CORS,所以如果您无法控制 API 开发,我猜是这样,唯一的方法是通过您的代理进行代理自己的网络服务器。
如果你有 nginx:
https://www.nginx.com/resources/admin-guide/reverse-proxy/
如果您使用的是 apache:
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html
请注意,jquery 或任何其他 javascript 框架对此没有帮助,因为它是浏览器限制。它似乎没有 crossdomain.xml 文件,因此闪存也无济于事。
The docs 声明 "Some API calls are available with CORS headers if you add a cors=true parameter to the request." 但您拨打的电话似乎并非如此。
似乎还有另一个允许跨源请求的调用:
https://blockchain.info/ru/q/24hrprice
所以只需像这样调整您的通话:
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
我有这样的代码:
<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
但它不起作用,因为 api 在不同的域中。有没有办法以某种方式修复它?我不想使用 jquery
它似乎不支持 CORS,所以如果您无法控制 API 开发,我猜是这样,唯一的方法是通过您的代理进行代理自己的网络服务器。
如果你有 nginx: https://www.nginx.com/resources/admin-guide/reverse-proxy/
如果您使用的是 apache: http://httpd.apache.org/docs/2.2/mod/mod_proxy.html
请注意,jquery 或任何其他 javascript 框架对此没有帮助,因为它是浏览器限制。它似乎没有 crossdomain.xml 文件,因此闪存也无济于事。
The docs 声明 "Some API calls are available with CORS headers if you add a cors=true parameter to the request." 但您拨打的电话似乎并非如此。
似乎还有另一个允许跨源请求的调用:
https://blockchain.info/ru/q/24hrprice
所以只需像这样调整您的通话:
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