[英]Php - how to encode an array as json and send it back
Allow me to preface this by saying that I looked at multiple SO posts on this and I am still lost. 首先,请允许我说我看过多个SO帖子,但我仍然迷路。
So in my php code I am fetching data from my database and then I am trying to insert it into an array as follows: 因此,在我的php代码中,我从数据库中获取数据,然后尝试将其插入数组,如下所示:
$arrayResult = array();
foreach ($result as $item) {
array_push($arrayResult, array("type" => $item['type'],
"count" => $item['count'])
);
}
echo json_encode($arrayResult);
My problem is as follows, the only time my JS shows any data is when I just print out the data on a successful AJAX call, any attempts at manipulating it fail totally. 我的问题如下,我的JS仅显示一次成功的AJAX调用中的打印数据时,操纵它的任何尝试都完全失败了。 As in, no data shown at all.
如图所示,完全没有数据显示。
var arrayResult = null;
$.get("../php/displayGraph.php",
function (data) {
arrayResult = (data);
var result = JSON.parse(arrayResult);
$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
The result of this is: 结果是:
[{"type":"Entertainment","count":"4"},{"type":"Other","count":"31"},{"type":"Politics","count":"50"},{"type":"Sports","count":"3"},{"type":"Technology","count":"9"}]
I am honestly at a loss in terms of what I even need to do to make it work. 老实说,我什至需要做些什么才能使它工作。 And here I thought java was bad with json.
在这里,我认为Java对json不利。
Try like this, 这样尝试
$.get("../php/displayGraph.php",
function (data) {
$.each(data, function (i,item){
console.log(item.type + " === " +item.count);
}
/*arrayResult = (data);
var result = JSON.parse(arrayResult);*/
//$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
Not sure why, but the following works 不知道为什么,但是以下工作
$.get("../php/displayGraph.php",
function (data) {
var result = JSON.parse(data);
$("#results").html(data);
console.log(result[1][0].count);
}
);
Certainly is a 2D array the way my php makes it, but i did not think this would be how to do as all the other tutorials i saw never had it like this. 当然是2D数组,这是我的php制作它的方式,但是我不认为这将是我的方法,因为我看到的所有其他教程都从来没有像这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.