[英]How to get data from json_encode?How to get respone by using AJAX?
I want to get use and its status in php from this json_encode response.How do I get it?我想从这个 json_encode 响应中获取使用及其在 php 中的状态。我如何得到它? Request Like json_encode(array('online' => $status))
请求像 json_encode(array('online' => $status))
{"online":[{"user":"1004","status":"Unmonitored"},
{"user":"1005","status":"Unmonitored"},
{"user":"1006","status":"Unmonitored"},
{"user":"2501","status":"Unmonitored"},
{"user":"2502","status":"Unmonitored"},
{"user":"2503","status":"Unmonitored"},
{"user":"2504","status":"Unmonitored"}]}
You can decode JSON using the json_decode() function like so:您可以使用 json_decode() 函数解码 JSON,如下所示:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
(json_decode($json);
?>
Another Example (read a specific object):另一个示例(读取特定对象):
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$obj = json_decode($json); //read a specific object
print $obj->{'a'}; // 1
?>
UPDATE I see you updated your question to 'How to get response by using AJAX?'更新我看到您将问题更新为“如何使用 AJAX 获得响应?”
//start ajax request
$.ajax({
url: "data.json",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//do what you want to do here
}
});
PHP 5.4 offers the JSON_PRETTY_PRINT
option for use with the json_encode()
call. PHP 5.4 提供了
JSON_PRETTY_PRINT
选项用于json_encode()
调用。
http://php.net/manual/en/function.json-encode.php http://php.net/manual/en/function.json-encode.php
<?php
$json_string = json_encode($data, JSON_PRETTY_PRINT);
?> ?>
Seems json_decode
is the function you are looking for.似乎
json_decode
是您正在寻找的功能。
<?php
$data = '{"online":[
{"user":"1004","status":"Unmonitored"},
{"user":"1005","status":"Unmonitored"},
{"user":"1006","status":"Unmonitored"},
{"user":"2501","status":"Unmonitored"},
{"user":"2502","status":"Unmonitored"},
{"user":"2503","status":"Unmonitored"},
{"user":"2504","status":"Unmonitored"}
]}';
// json_decode produces stdClass object
$decoded_std = json_decode($data);
var_dump($decoded_std->online[0]->status); // "Unmonitored"
// json_decode produces associative array
$decoded_array = json_decode($data, true); // note the second param
var_dump($decoded_array['online'][0]['status']); // "Unmonitored"
Check the hosted working example here http://ideone.com/xaCx4E .在此处查看托管的工作示例http://ideone.com/xaCx4E 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.