【问题标题】:How to speed up the loading time of my web page while parsing JSON file from URL从 URL 解析 JSON 文件时如何加快网页的加载时间
【发布时间】:2019-02-16 18:37:13
【问题描述】:

我从一个 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 页面,如果你知道怎么做的话:)。

【问题讨论】:

  • 清除您的 api 密钥以确保安全!
  • 以上都说了!您现在需要删除旧的并生成新的 API 密钥。任何人都可以在任何地方使用该密钥访问 guildwars api 以查看您的帐户信息,并且它具有广泛的权限。在这里做:account.arena.net/applications

标签: php html json


【解决方案1】:

AJAX 是一种从前端(javascript)异步向服务器发出请求的简单方法。因此,在您的示例中,您希望达到 guildwars 端点。正如您在下面的代码中看到的,我向您的端点发出 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多