如何在HTML中展示API输出数值?需求:显示USD-GBP实时汇率
Hey there! Here's a simple HTML solution that will fetch the USD-GBP rate from currencylayer's API and only display the numerical value you're looking for:
<!DOCTYPE html> <html> <head> <title>USD-GBP Exchange Rate</title> </head> <body> <!-- This div will hold our rate --> <div id="rate-container"></div> <script> // Don't forget to replace this with your actual currencylayer API key! const YOUR_API_KEY = 'YOUR_ACTUAL_ACCESS_KEY'; const apiEndpoint = `http://apilayer.net/api/live?access_key=${YOUR_API_KEY}¤cies=GBP&source=USD&format=1`; // Fetch the data from the API fetch(apiEndpoint) .then(response => response.json()) .then(data => { // Check if the API request was successful if (data.success) { // Extract just the numerical rate from the quotes object const usdToGbpRate = data.quotes.USDGBP; // Update the div to show only the number document.getElementById('rate-container').textContent = usdToGbpRate; } else { // Handle cases where the API returns an error (like invalid key) document.getElementById('rate-container').textContent = 'Failed to load rate'; } }) .catch(error => { // Handle network issues or other unexpected errors document.getElementById('rate-container').textContent = 'Error loading rate'; console.log('Something went wrong:', error); }); </script> </body> </html>
Quick Tips:
- Swap out the API key: You must replace
YOUR_ACTUAL_ACCESS_KEYwith the key you obtained from currencylayer.com. Without a valid key, the API won't return the rate you need. - Fixed the typo: I corrected the
currencies=BBPmistake from your original URL tocurrencies=GBPas you mentioned—important to get that right! - Error handling: I added basic checks so you'll see a helpful message instead of a blank page if something goes wrong (like a bad key or no internet).
- Clean display: The script pulls just the
USDGBPvalue from the API's response and inserts it directly into the div—no extra text, just the numerical rate (e.g., 0.71).
Save this as an HTML file, plug in your API key, and open it in a browser—it will automatically load and show the latest USD-GBP exchange rate.
内容的提问来源于stack exchange,提问作者GNY
相关产品推荐
相关产品推荐

