我收到了一个来自URL的json数据(这是芹菜的flower插件)。样品:

{
  "celery@s1": {
    "scheduled": [],
    "stats": {
      "clock": "2535550",
      "pid": 26002,
      "broker": {
        "transport_options": {},
        "login_method": "AMQPLAIN",
        "hostname": "127.0.0.1",
        "alternates": []
      },
      "prefetch_count": 8,
      "total": {
        "stone": 2602,
        "wood": 34
      }...

我尝试解析它,并使用PHP和JS创建自定义统计页面。
用php解析:
<?php
$url = 'http://127.0.0.1:5555/api/workers';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json['celery@s1']['stats']['total'] as $item) {
    echo json_encode($item['wood']);
}

?>

使用更新计时器从php脚本获取数据的JS:
function getFromFile() {
    $.get("s_updater.php",function(response) {
        response = JSON.parse(response);
        console.log(response)
        $("#field-1").html(response);
    });
}

$(document).ready(function() {
    var period = 1000;
    getFromFile();
    var per = setInterval(function() {
        getFromFile();
    }, period);
});

但看起来我在某个地方犯了个错误,现在我被卡住了。有没有更好的办法?
我只想从URL的json中得到“wood”:34并在html页面上显示值。

最佳答案

$json = json_decode($content, true);

 echo $json['celery@s1']['stats']['total']['wood'];

您不必使用循环或JSON来发送单个值,只需回显它即可。
JS代码
function getFromFile() {
    $.get("s_updater.php",function(response) {
        console.log(response)
        $("#field-1").html(response);
    });
}

关于javascript - 使用PHP和JS从URL解析JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42459267/

10-11 22:14
查看更多