我收到来自URL(这是芹菜的插件)的数据的json。示例:使用PHP和JS从URL解析JSON
{
"[email protected]": {
"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['[email protected]']['stats']['total'] as $item) {
echo json_encode($item['wood']);
}
?>
和JS从PHP脚本与更新计时器获取数据:
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页面上显示值。
请从'console.log'输出更明确的答案 –
对不起,我摆脱了大部分东西,忘记删除逗号。我在问题中编辑了JSON。 Console.log显示: 'SyntaxError:JSON解析错误:无法识别的令牌'<''。 –
@SamBronson你想从PHP服务器获得一个键值对吗? –