dqyitt2954 2019-02-16 18:37
浏览 159

如何在从URL解析JSON文件时加快我的网页加载时间

I'm getting data from a json file, accessed from URL,and the loading time is really long. However this website(https://gw2efficiency.com/) is actually getting same data, but some way manages to show them only when they are ready, and i would like to do it too.

I haven't found any clear way of doing this, i saw it might be an AJAX call but never used that.

this is where i show the data

<header>
<?php require 'getbag.php'?>
</header>
  <body>
    <div>
      <span>Argent flat actuel: </span><br>
      <?php echo "  ".$gold ?><img alt="gold" src="gw2/images/gold_coin.png"><?php echo "  ".$silver ?><img  alt="silver" src="gw2/images/silver_coin.png"><?php echo "  ".$copper ?><img alt="copper" src="gw2/images/copper_coin.png">
    </div>
  </body>

And this is the file i call to get the data from the json file

getbag.php

<?php
$apikey = '<apikey>';
$headers = array(
'Accept-Language: fr',
'Authorization: Bearer '.$apikey.'',
);
$url='https://api.guildwars2.com/v2/account/wallet';

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$array1 = json_decode($result, true);
$value[] = $array1[0]['value'];
$id[] = $array1[0]['id'];
$total=$value[0];
$copper = substr($total, -2, 2);
$silver = substr($total, -4, 2);
$gold   = substr($total, 0, -4);


 ?>

I would like to see the html page instantly, if you have any idea how :).

  • 写回答

1条回答 默认 最新

  • doskmc7870 2019-02-17 05:40
    关注

    AJAX is a simple way to make a request to to a server asynchronously from the frontend(javascript). So in your example you wish to hit the guildwars endpoint. As you can see in the code below, I make an ajax request to your endpoint, set the same headers and define a callback for when the response is successful. console.log(JSON.parse(this.responseText)); will log the response to your browsers console. Then it's just a matter of accessing the javascript object.

    <script>
    function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          // view the this.responseText in your browser console log
          console.log(JSON.parse(this.responseText));
        }
      };
      xhttp.open("GET", "https://api.guildwars2.com/v2/account/wallet", true);
      xhttp.setRequestHeader("Accept-Language", "fr");
      xhttp.setRequestHeader("Authorization", "Bearer <apikeyGoesHere>");
      xhttp.send();
    } 
    loadDoc();
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记