You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

CoinMarketCap API v2 JSON结构访问及多代币价格展示函数开发求助

Fixing CoinMarketCap API v2 Adaptation & Multi-Token Price Display with jQuery

Hey there! Let's work through updating your code for CoinMarketCap's API v2 and adding multi-token price support. The biggest change from v1 is the JSON structure—v1 returned a flat array of token objects, but v2 nests everything under a data object using numeric token IDs as keys.

First, let's fix your original Bitcoin price code for v2:

Updated Single Token (Bitcoin) Code

Instead of looping through an array, we can directly fetch Bitcoin's data (it has a fixed ID of 1) and access the price via the nested path data.data.quotes.USD.price:

<script type="text/javascript">
// Fetch Bitcoin's data directly by its ID to minimize payload
$.get("https://api.coinmarketcap.com/v2/ticker/1/", function(data, status) {
    // Format the price to 2 decimal places for readability
    const formattedPrice = `$${data.data.quotes.USD.price.toFixed(2)}`;
    $("#bitcoin").html(formattedPrice);
}).fail(function() {
    // Handle API errors gracefully
    $("#bitcoin").html("Price unavailable");
});
</script>

Multi-Token Price Display

To show prices for multiple tokens efficiently, we can create reusable functions. Here are two approaches:

Approach 1: Individual Requests (Simple)

This is straightforward for small numbers of tokens, with per-token error handling:

<script type="text/javascript">
function loadTokenPrice(tokenId, targetElementId) {
    $.get(`https://api.coinmarketcap.com/v2/ticker/${tokenId}/`, function(data) {
        const price = data.data.quotes.USD.price;
        $(`#${targetElementId}`).html(`$${price.toFixed(2)}`);
    }).fail(function() {
        $(`#${targetElementId}`).html("Error loading price");
    });
}

// Load prices for Bitcoin, Ethereum, and Ripple
loadTokenPrice(1, "bitcoin");       // Bitcoin (ID: 1)
loadTokenPrice(1027, "ethereum");   // Ethereum (ID: 1027)
loadTokenPrice(52, "ripple");       // Ripple (ID: 52)
</script>

Approach 2: Batch Request (More Efficient)

For multiple tokens, using a single batch request reduces network calls. CoinMarketCap allows fetching multiple tokens at once by passing comma-separated IDs:

<script type="text/javascript">
function loadBatchTokenPrices(tokenElementMap) {
    // Extract token IDs from our mapping object
    const tokenIds = Object.keys(tokenElementMap).join(",");
    
    $.get(`https://api.coinmarketcap.com/v2/ticker/?id=${tokenIds}`, function(data) {
        // Loop through each token in the response
        Object.values(data.data).forEach(token => {
            const targetId = tokenElementMap[token.id];
            if (targetId) {
                const formattedPrice = `$${token.quotes.USD.price.toFixed(2)}`;
                $(`#${targetId}`).html(formattedPrice);
            }
        });
    }).fail(function() {
        // Show error for all tokens if the batch call fails
        Object.values(tokenElementMap).forEach(elementId => {
            $(`#${elementId}`).html("Price unavailable");
        });
    });
}

// Define which token IDs map to which DOM elements
const tokenMap = {
    1: "bitcoin",
    1027: "ethereum",
    52: "ripple",
    1839: "binancecoin" // Add more tokens here as needed
};

// Load all prices in one go
loadBatchTokenPrices(tokenMap);
</script>

Key Notes

  • Token IDs: You'll need to use each token's numeric ID (e.g., Bitcoin = 1, Ethereum = 1027). You can find these IDs by checking the full ticker list from the API or CoinMarketCap's website.
  • Nested Path: The price lives at data.data.quotes.USD.price for single requests, or token.quotes.USD.price when iterating over batch response data.
  • Error Handling: Added .fail() callbacks to ensure your UI doesn't show empty spaces if the API is unavailable.
  • Formatting: Used toFixed(2) to display prices with two decimal places—adjust this number if you need more/less precision.

内容的提问来源于stack exchange,提问作者jpp

火山引擎 最新活动