首页 > 解决方案 > JavaScript API fetch 在第一次加载时不起作用

问题描述

我正在开发这个货币转换应用程序并从https://exchangeratesapi.io/获取 API

该应用程序可以正常工作,只是它仅在刷新时获取 api。我在body标签中使用onload。

知道如何在不刷新的情况下使其在首次加载时工作吗?

提前致谢

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>JS Bin</title>

        <script type="text/javascript" src="indexCurrencyFirst.js" ></script>
        <script type="text/javascript" src="indexCurrency.js" ></script>
        <link rel="stylesheet" type="text/css" href="styleCurrency.css">  

</head>
<body onload="convertCurrencyRight()" >

    <nav>
      <ul class="navbar">
        <li id="logo"><img src="Assets/Logo_openCurren.svg"></li> 
        <li id="date">Fecha</li>
      </ul>
    </nav>
    <div class="wrapper" >
        <div id="containerFrom">
          <input id="fromQuantity" type="number" value="1" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()"/>
          <select id="from" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">


          </select>
         </div>   
         <div id="arrow"><img src="Assets/Arrow.svg"> </div>

        <div id="containerTo"> 
         <input id="toQuantity" type="number" value="0" onchange="convertCurrencyLeft()" onkeyup="convertCurrencyLeft()"/>
          <select id="to"  onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
            <option value="EUR"  selected>EUR</option>
          </select>
        </div>
    </div>    

    <div class="wrapper"  >
        <div id="containerCValues">
            <p id="currentRateA"> 1 Eur = 0.89 Gbp  </p>
            <p id="currentRateB"> 1 Gbp = 1.12 Eur  </p>
        </div>
    </div>


</body>
</html>

我的 JS 文件

加载到头部 indexCurrencyFirst

//fill the select options with the available currencies      

fetch("https://api.exchangeratesapi.io/latest?base=")
      .then((resp) => resp.json())
      .then(function(data){
        var allRates = data.rates;
        var selectA = document.getElementById("from");
         var selectB = document.getElementById("to");
         allRates = Object.entries(allRates)


         for(var i = 0; i < allRates.length; i++) {
            var opt = allRates[i][0];
            var el = document.createElement("option");
            el.textContent = opt;
            el.value = opt;
             if(opt==="GBP"){
                 var selectedAtt=document.createAttribute("selected");
                 el.setAttributeNode(selectedAtt);
             }
            selectA.appendChild(el);

            var la = document.createElement("option");
             la.textContent = opt;
             la.value = opt;
             selectB.appendChild(la);
        }   

        })

        .catch(function(error) {
        console.log(error);
        });

以及转换费率的函数

function convertCurrencyRight() {
    var fromCurrency = document.getElementById("from").value;
    var toCurrency = document.getElementById("to").value;
    console.log(toCurrency);

    fetch("https://api.exchangeratesapi.io/latest?base=" + fromCurrency)
      .then((resp) => resp.json())
      .then(function(data){
        //if both currencies are the same return identical values
        (fromCurrency===toCurrency) ? 
        (document.getElementById("toQuantity").value = document.getElementById("fromQuantity").value,
        document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + "...",
        document.getElementById("currentRateB").textContent= "")
        :
        //otherwise return the top value as the multiplication of top currency rate by the amount specied below
        (document.getElementById("toQuantity").value = (data.rates[toCurrency]*document.getElementById("fromQuantity").value).toFixed(3),
        //change the single amount values
        document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + (data.rates[toCurrency]).toFixed(6) + " " + toCurrency,
        document.getElementById("currentRateB").textContent= "1 " + toCurrency + " = " + (1/data.rates[toCurrency]).toFixed(6) + " " + fromCurrency)
        //load the date of the current rates
        var date = document.getElementById("date");
        date.innerHTML = "LAST UPDATED " +
        data.date.split("-").reverse().join("-");


        })

        .catch(function(error) {
        console.log(error);
        });
}


function convertCurrencyLeft() {
    ...
}

任何想法如何解决这个问题。我尝试使用准备好文档的jQuery而不是运气好

标签: javascripthtmlapifetchrefresh

解决方案


我只是搭上onload你的身体标签,然后使用 Jquery$(document).ready()并将你的电话打到 `convertCurrencyRight() 那里。在我的小提琴中,这似乎工作正常。

$(document).ready(function() {
    convertCurrencyRight();
});

推荐阅读