使用JS和PHP

时间:2015-12-24 08:06:13

标签: javascript php jquery json

我一直在寻找一种延迟从API加载JSON数据的方法(因为我在页面上进行了大约5次以上的API调用) 我发现了这个:https://github.com/rpnzl/jquery-lazyjson/tree/v1.0

看起来像一个很好的课程,但由于我在我的网站上使用PHP并且这个类的调用是使用JavaScript,我不知道如何将它与我的PHP代码结合使我的网站加载& #34;按部分"。

我的目标是快速加载可能的内容,然后逐个动态加载每个API调用,以使网站运行更顺畅。

我想听听处理多个API调用和动态获取数据的任何想法。

这就是我现在提取数据的方式。所有PHP和大约7秒的加载:

    //Get the match!
    $matches = $data->getMatchHistory($playerId,$characterId); //Returns an array of each match found
    if ($matches == 0)
    {
    //Todo when user not in game
    echo '<div class="alert alert-danger"><h2>We\'re sorry..<br/>There are no matches for this player with '.$playerId.'</div>';
        } else {
            for($i=0;$i<sizeof($matches)-1;$i++)
            {
                $match[$i] = new Match();
                $match[$i]->matchId = $matches[$i]['matchId'];
                $match[$i]->charName = $data->getCharacterName($matches[$i]['character']);
                $match[$i]->stats = $data->getMatchStats($match[$i]->matchId); // Makes another API call and returns the match statistics. One Match = 2 API calls
            }
            ?>
            <h2><?=$playerName?> Match History</h2>
            <?php           
            for ($i=0;$i<sizeof($matches)-1;$i++)
            {
?>
<!--ALOT OF HTML,CSS, AND data fetching this way:-->
<?=matches[$i]->someData;?>

<?php
            }
            ?>

1 个答案:

答案 0 :(得分:0)

您也可以使用PHP解码并从API调用中获取JSON。

$JSON = file_get_contents("API-URL.json");

如果我们知道file_get_contents将页面返回给变量(在本例中为JSON字符串),我们就可以使用PHP解码收到的JSON。

$Array = json_decode($JSON, 1);

假设您有一个{"playerid": 1298134, "gender": "male"}的json字符串,您可以通过$Array["playerid"]$Array["gender"]访问这些字符串,然后返回变量。

如果JSON中有一个数组,也是如此,例如{"playerid": 1298134, "gender": "male", "personal": {"fname": "Kieran", "lname": "Cross"}}可以$Array["playerid"]$Array["personal"]["fname"]

访问

如果您想快速解码页面顶部的API,可以轻松完成

$Array = json_decode(file_get_contents("API-Page.json"), 1);

您可以在此here, on the PHP documentation上阅读更多内容。