down2323 2015-02-08 07:09
浏览 35
已采纳

使用ajax,php和javascript进行实时json数据更新

I am making a simple bitcoin price ticker overview website, and I am using the API's of 8 different bitcoin exchanges. All are JSON.

<?php
function getPrice($url){
    $decode = file_get_contents($url);
    return json_decode($decode, true);
}

$blockchain = getPrice('https://blockchain.info/ticker');
$blockchainPrice = $blockchain["USD"]["last"];
?>

And im just echoing it in a table

   <table>
        <tr> <th> Current prices</th><th> Volume</th> </tr>
        <tr>
        <td>Blockchain.info</td>
        <td>$<?php echo $blockchainPrice; ?></td>
        </tr>
</table>

But, I need to update the prices in real time, every 20 seconds, but in this code, ehenever i refresh, i get a changed price, and im going to cater a large audience, and i dont want to hit the api call limits, so i want the price to be updated every 20 seconds only.

I tried to use ajax to update values in real time but it isnt working

Here is my ajax code

$.ajax({
        url: 'https://blockchain.info/ticker',
        dataType: 'json',
        cache: false,
        success: function(result) {
            $('test').html(result.last);
        }
    });
}, 20000);

and i made a div with id="test"

Im expecting the price to be echoed, and updated every 20 seconds. but it isn't happening

  • 写回答

1条回答 默认 最新

  • dony39517 2015-02-08 07:20
    关注

    This is the code that would have worked:

    function update() {
        $.getJSON('https://blockchain.info/ticker').done(function(res) {
            $('#test').html(res.last); 
        });
    }
    
    var interval = window.setInterval(update, 20000);
    

    The reason it doesn't is because blockchain.info does not have CORS headers, nor JSONP, for their ticker API. That means they don't want you to be able to use this via javascript, and they want to be able to throttle requests made by a server.

    What you can do, however, is have your web server use their ticker API every x seconds. Then in javascript, have your clients send an AJAX request to your server every 20 seconds. Good luck :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)