2017-08-08 57 views
0

如何顯示存儲在JSON API數組中的特定變量的值?如何顯示來自JSON API的特定信息?

例如,如何使用coinmarketcaps JSON API(https://api.coinmarketcap.com/v1/ticker/bitcoin/)在特定的wordpress文章中以美元顯示當前的比特幣價格?

的API給我下面的輸出:

[ 
{ 
    "id": "bitcoin", 
    "name": "Bitcoin", 
    "symbol": "BTC", 
    "rank": "1", 
    "price_usd": "3351.98", 
    "price_btc": "1.0", 
    "24h_volume_usd": "1455740000.0", 
    "market_cap_usd": "55289274334.0", 
    "available_supply": "16494512.0", 
    "total_supply": "16494512.0", 
    "percent_change_1h": "0.55", 
    "percent_change_24h": "3.45", 
    "percent_change_7d": "17.52", 
    "last_updated": "1502145551" 
} 
] 

我只需要顯示「price_usd」壽的價值。

我一直試圖做這種方式,但它沒有工作:

<script> 

    var btcPrice; 

    function UpdateBtcPrice(){ 
     $.ajax({ 
      type: "GET", 
      url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/", 
      dataType: "json", 
      success: function(result){ 
       btcPrice = result[0].price_usd; 
      }, 
     error: function(err){ 
      console.log(err); 
     } 
     }); 
    } 
</script> 

任何幫助,將不勝感激!

回答

1

你需要調用函數來執行請求:

 

     var btcPrice; 

     function UpdateBtcPrice(){ 
      $.ajax({ 
       type: "GET", 
       url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/", 
       dataType: "json", 
       success: function(result){ 
        btcPrice = result[0].price_usd; 
       }, 
      error: function(err){ 
       console.log(err); 
      } 
      }); 
     } 

     UpdateBtcPrice(); 

+0

我知道。我仍然無法讓它工作。我認爲我必須將函數添加到當前wordpress主題的functions.php文件中,並且可以隨後請求無論我需要它的函數。當我將新功能添加到它的functions.php – Voxcon

+0

@ Voxcon - 你不能在functions.php中使用javascript或jQuery,你必須把這個功能放在模板文件裏面,它可以從那裏訪問客戶端 - 瀏覽器。 – kastriotcunaku

+0

啊我明白了。在js文件夾中保存了UpdateBtcPrice.js函數,現在我可以通過php函數調用它!謝謝! – Voxcon

1

你可以試試這個代碼

<?php 
    //get data with api call 
    $response = file_get_contents('https://api.coinmarketcap.com/v1/ticker/bitcoin/'); 
    $response = json_decode($response); 

    echo $response[0]->price_usd;//print the value 
?> 
+0

Souvik Sikdar非常感謝你!你的方法更簡單,效果更好! – Voxcon