doumen9709 2017-01-24 10:23
浏览 52
已采纳

PHP如何稍后设置内容或是否加载? [关闭]

Hello I have a website which loads data from an api to show the newest stats. I am storing it for 10 minutes to prevent loading api calls every time. Since there are many api calls it takes at first time like 5-10 seconds to finish loading the website which looks like the website would be down.

Currently I am using pure php for functionalities. There are functions like GetTotalEarnings() - just a file_get_contents($url) to receive a json content and decode it and put it to a table which I can use for 10 minutes. After 10 minutes it will call all apis again to refresh the values (if the page get reloaded of course).

To solve this my idea was to load the content first and show the content and then load the data to set values later. But I don't know where to start. I know jquery can do this with a call back but its javascript. I don't know what tot do there

Two examples how looks currently

<h1 class=""><center>Earnings Total: <?php echo GetTotalEarnings() . " (Latest update: " . GetLatestUpdateTime() . ")"; ?></center></h1>


<h1 class="">This Month</h1>
<div class="col-xs-6 col-sm-6 col-md-3">
    <div class="box c1 center-block">
        <h4 class="blue">Today</h4>
        <span class="icon blue"><i class="fa fa-usd"></i></span>
        <span class="price-large blue"><?php echo round(GetTodayEarnings(), 2); ?></span>
    </div>
</div>
  • 写回答

2条回答 默认 最新

  • dongxi7704 2017-01-24 10:31
    关注

    Instead of requesting the API data on a user request, I would instead have a background script/program running every 10 minutes which caches the results in memcached or MySQL. Then when a user requests the data, return the cached results. If the API takes 10+ seconds to process, then without looking at the code to potentially optimise it we have to assume 10+ seconds is just how long it takes to process. Caching is the only way to speed up the user request without optimising the API.

    You could use JavaScript to async load the script then modify the document once the page has loaded. Below is an example using Jquery.

    $(document).ready(function(){
            $.ajax({
                type: "GET",
                url: "myApiCalls.php",
                dataType: 'json',
                data: queryString,
                success: function(data) {
                    // ...
                }
            });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题