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

时间:2019-02-16 18:37:14

标签: php html json

我从json文件中获取数据,可以通过URL访问,并且加载时间非常长。但是,该网站(https://gw2efficiency.com/)实际上正在获取相同的数据,但是某种方式设法仅在它们准备好后才显示它们,我也想这样做。

我还没有找到任何明确的方法,我看到这可能是AJAX调用,但从未使用过。

这是我显示数据的地方

<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>

这是我用来从json文件中获取数据的文件

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);


 ?>

如果您知道如何:),我想立即查看html页面。

1 个答案:

答案 0 :(得分:0)

AJAX是一种从前端(javascript)异步向服务器发出请求的简单方法。因此,在您的示例中,您希望达到“激战”终点。如您在下面的代码中看到的,我向您的端点发出ajax请求,设置相同的标头,并为响应成功时定义了回调。 console.log(JSON.parse(this.responseText))会将响应记录到浏览器控制台。然后,只需访问javascript对象即可。

<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>