如何使用 AJAX 从复杂的 API 中提取数据并显示在 .php 页面上

How to pull data from a complicated API using AJAX and display on a .php page

现在,我正在帮助的网站纯粹是 php、html、css 和一些 javascript.

我使用 php 从网络上提取数据-API 并 post 将其提取到网页上。

例如:

$pool = json_decode(file_get_contents("http://api.link:port/api/v1/Pool-Avian/"), false); 
//Removed API link since I don't have the owner's permission for specifics at this time.
        <table class="table table-sm table-borderless table-striped mt-md-0 mt-3">
            <tbody>
                <tr>
                    <th>Block Reward:</th>
                    <td id="lastBlockReward">~2475 AVN</td>
                </tr>
                <tr>
                    <th>Blockchain Height:</th>
                    <td>     
                        <?php echo $pool->body->primary->network->height; ?>
                    </td>
                </tr>
                <tr>
                    <th>Network Hashrate</th>
                    <td>
                        <?php echo hashRateCalculator($pool->body->primary->network->hashrate); ?>
                    </td>
                </tr>
                <tr>
                    <th>Network Difficulty</th>
                    <td>
                        <?php echo hashRateCalculator($pool->body->primary->network->difficulty); ?>
                    </td>
                </tr>
                <tr>
                    <th>Blocks Found By Pool</th>
                    <td>
                        <?php echo $pool->body->primary->blocks->valid; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

API是这样的:

{"version":"0.0.3","statusCode":200,"headers":{"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Allow-Methods","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Content-Type":"application/json"},"body":{"primary":{"config":{"coin":"Avian","symbol":"AVN","algorithm":"x16rt","paymentInterval":21600,"minPayment":0.01,"recipientFee":0.01},"blocks":{"valid":83,"invalid":0},"shares":{"valid":20734,"stale":124,"invalid":0},"hashrate":{"shared":68131817.9050706,"solo":0},"network":{"difficulty":738.1659173695874,"hashrate":116186636292.9936,"height":541555},"payments":{"last":1647460164235,"next":1647460254235,"total":198724.56746191},"status":{"effort":61.25198558663565,"luck":{"luck1":7.93,"luck10":64.47,"luck100":89.27},"miners":3,"workers":3}},"auxiliary":{"config":{"coin":"","symbol":"","algorithm":"","paymentInterval":0,"minPayment":0,"recipientFee":0},"blocks":{"valid":0,"invalid":0},"shares":{"valid":0,"stale":0,"invalid":0},"hashrate":{"shared":0,"solo":0},"network":{"difficulty":0,"hashrate":0,"height":0},"payments":{"last":0,"next":0,"total":0},"status":{"effort":0,"luck":{"luck1":0,"luck10":0,"luck100":0},"miners":0,"workers":0}}}}

我查看了一些网站和教程以了解如何执行此操作,但我似乎无法让它们工作...

现在,我的测试页面是这样的:

<script>
            miner = 0;
            function updateData() { //Obtain data from API and push to website//
                miner = miner + 1;
                document.getElementById("minerBottom").innerHTML = miner;
            }
            window.onload = function () {
                webHandler();
            };
            
            function webHandler() {
                const xhr = new XMLHttpRequest();
                xhr.open("GET", "http://api.link:port/api/v1/Pool-Avian/", true); 
                //again - API redacted//
                xhr.onload = function () {
                    if (this.status === 200) {

                        // Changing string data into JSON Object
                        obj = JSON.parse(this.responseText);

                        // Getting the ul element
                        let list = document.getElementById("list");
                        str = "";
                        for (key in obj.data) {
                            str +=
                                    `<li>${obj.data[key].employee_name}</li>`;
                        }
                        list.innerHTML = str;
                    } else {
                        console.log("File not found");
                    }
                };
                xhr.send();
            }
        </script>

测试元素为:

<div class="totalBox">
    <div class="totalValue" id="minerTop">
        Miners
    </div>
    <div class="totalValue" id="minerBottom">

    </div>
</div>
<div class="totalBox">
    <div class="totalValue" id="workerTop">
        Workers
    </div>
    <div class="totalValue" id="workerBottom">
        0
    </div>
</div>
<div class="totalBox">
    <div class="totalValue" id="blockTop">
        Blocks
    </div>
    <div class="totalValue" id="blockBottom">
        0
    </div>
</div>

它让我迷失在“获取 ul 元素”部分 - 我不确定它试图做什么,或者我如何将它变成我需要它做的事情。

我想要它做的是找到我正在寻找的对(例如 body->primary->status->miners)并将其显示在适当的 <div>

根据答案 - 将脚本更新为:

function webHandler() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "http://api.link:port/api/v1/Pool-Avian/", true);
    //again - API redacted//
    xhr.onload = function () {
        if (this.status === 200) {
            // Changing string data into JSON Object
            obj = JSON.parse(this.responseText);

            // get "miners" from API response. 
            // This does not validate if the value is actually in the object!
            let miners = obj.body.primary.status.miners;
            // get DOM element by id
            let minersElement = document.getElementById('minerBottom');
            // set value of miners as text in DOM
            minersElement.innerText = miners;

        } else {
            } else {
        console.log("File not found");
    }
        }
    };
    xhr.send();
}

div 中没有显示

对于矿工,这是您测试页脚本中的示例。

if (this.status === 200) {
    // Changing string data into JSON Object
    obj = JSON.parse(this.responseText);

    // get "miners" from API response. 
    // This does not validate if the value is actually in the object!
    let miners = obj.body.primary.status.miners;
    // get DOM element by id
    let minersElement = document.getElementById('minerBottom');
    // set value of miners as text in DOM
    minersElement.innerText = miners;
    
} else {
    console.log("File not found");
}
                

请注意,如果 API 的响应有效,这不包括任何清理检查或验证。