【问题标题】:Calling a API twice on same page fails second time in WordPress在同一页面上调用 API 两次在 WordPress 中第二次失败
【发布时间】:2023-01-13 09:45:11
【问题描述】:

代码在 codepen 中运行良好,但在尝试使用短代码在 WordPress 页面中运行时它没有运行。可能是什么原因。此代码下方的所有剩余内容也未显示。尤其是当试图在没有显示的页面中运行 js 时。

  <script>
    // Fetch the exchange rates from the API
    fetch(`https://api.fastforex.io/fetch-multi?from=AED&to=USD,EUR,GBP,INR,AUD,CAD,SGD,CHF,MYR,JPY&api_key=xxxxx-xxx-xxx`)// API key on purpose
      .then(response => response.json())
      .then(data => {
        // Update the exchange rates in the table
        document.getElementById("eur").innerHTML = data.results.EUR;
document.getElementById("gbp").innerHTML = data.results.GBP;
document.getElementById("chf").innerHTML = data.results.CHF;
document.getElementById("eur").innerHTML = data.results.EUR;
document.getElementById("gbp").innerHTML = data.results.GBP;
document.getElementById("chf").innerHTML = data.results.CHF;
document.getElementById("usd").innerHTML = data.results.USD;
document.getElementById("inr").innerHTML = data.results.INR;
document.getElementById("aud").innerHTML = data.results.AUD;
document.getElementById("cad").innerHTML = data.results.CAD;
document.getElementById("sgd").innerHTML = data.results.SGD;
document.getElementById("myr").innerHTML = data.results.MYR;
document.getElementById("jpy").innerHTML = data.results.JPY;

      });
  </script>
</body>

【问题讨论】:

  • 您的短代码功能是什么样的?你可以张贴吗?
  • 检查未关闭的功能。

标签: javascript wordpress api fetch fetch-api


【解决方案1】:

使用前排队了吗?

function enqueue_exchange_rate_script() {
    wp_enqueue_script( 'exchange-rate-script', get_stylesheet_directory_uri() . '/exchange-rate-script.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_exchange_rate_script' );



fetch(`https://api.fastforex.io/fetch-multi?from=AED&to=USD,EUR,GBP,INR,AUD,CAD,SGD,CHF,MYR,JPY&api_key=your_api_key`)
    .then(response => response.json())
    .then(data => {
        // Update the exchange rates in the table
        document.getElementById("eur").innerHTML = data.results.EUR;
        document.getElementById("gbp").innerHTML = data.results.GBP;
        document.getElementById("chf").innerHTML = data.results.CHF;
        document.getElementById("usd").innerHTML = data.results.USD;
        document.getElementById("inr").innerHTML = data.results.INR;
        document.getElementById("aud").innerHTML = data.results.AUD;
        document.getElementById("cad").innerHTML = data.results.CAD;
        document.getElementById("sgd").innerHTML = data.results.SGD;
        document.getElementById("myr").innerHTML = data.results.MYR;
        document.getElementById("jpy").innerHTML = data.results.JPY;
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 2021-04-02
    • 2010-12-21
    相关资源
    最近更新 更多