我收到來自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服務器獲得一個鍵值對嗎? –