代码之家  ›  专栏  ›  技术社区  ›  Snappysites

返回条带平衡,同时使用JS和PHP避免加载时间

  •  0
  • Snappysites  · 技术社区  · 2 年前

    我正在使用Stripe API在其仪表板上返回给定客户的余额/信用,尽管API需要很长时间才能运行,页面加载时间也很长,只需要一个数字就很麻烦。我特别不想把余额保存到数据库中,所以我考虑了其他选择。

    我已经编写了PHP API调用,将余额返回到我正在使用的新文件中 setInterval 函数,然后更新Div以显示平衡,这很好,尽管我根本不想重复这个函数,只是希望它加载并更新一次。我添加了一个预加载程序,理想情况下,我希望预加载程序在余额更新之前一直显示。显然我不能用 设置间隔 。我试过使用一些我知道的Javascript函数,比如window onload,但这根本不会更新余额?

    我知道这个功能不是我需要的选项,尽管我对Javascript知之甚少,任何帮助或建议都将不胜感激。以下是我目前拥有的:

    <script>
        setInterval(function() {
            $("#balance").load('stripebalance.php);
        }, 10000);
    </script>
    
    <div id="preloader">
        <div id="loader"></div>
    </div>
    
    <div id="balance">
    <h1>£-</h1>
    </div>
    
    <script>
    $(window).on('load', function(){
      setTimeout(removeLoader, 2000);
    });
    function removeLoader(){
        $("#preloader").fadeOut(500, function() {
          $("#preloader").remove(); 
      });  
    }
    </script>
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Phil    2 年前

    在我看来,你只想在加载数据后删除预加载程序。

    jQuery的 .load() 函数支持在请求完成后执行的回调函数

    jQuery(function($) {
      $("#balance").load("stripebalance.php", function() {
        $("#preloader").fadeOut();
      });
    });
    

    在这个过程中不需要任何间隔或超时。


    此外,现在快2023年了,你当然不需要jQuery

    const getStripeBalance = async () => {
      const res = await fetch("stripebalance.php");
      if (!res.ok) {
        throw new Error(`Fetch error: ${res.status} - ${res.statusText}`);
      }
      return res.text();
    }
    
    const stripeBalanceHtmlPromise = getStripeBalance();
    
    document.addEventListener("DOMContentLoaded", async () => {
      const balance = document.getElementById("balance");
      const loader = document.getElementById("preloader");
      const stripeBalanceHtml = await stripeBalanceHtmlPromise;
      balance.innerHTML = stripeBalanceHtml;
    
      loader.addEventListener("animationend", () => {
        loader.remove();
      });
      loader.classList.add("fadeOut");
    });
    
    .fadeOut {
      animation: fadeOut 0.5s linear forwards;
    }
    
    @keyframes fadeOut {
      0% {
        opacity: 1;
      }
      100% {
        opacity: 0;
      }
    }