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 :)

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

报告相同问题?