[英]json_encode on a PHP array returns a string
I've searched through the site and can't see a question quite like mine so I hope this isn't a copy. 我已经搜索了该网站,却找不到像我这样的问题,所以我希望这不是一个副本。
So I've got a PHP script which is supposed to return a JSON array to my AJAX, and I want to use the array to generate a URL. 因此,我有一个PHP脚本,该脚本应该将JSON数组返回到我的AJAX,并且我想使用该数组来生成URL。
However, even though I'm pretty sure I've got an array on the PHP end, when I json_encode I'm getting a simple string out on the other end. 但是,即使我非常确定我在PHP端都有一个数组,但是当我json_encode时,我在另一端得到了一个简单的字符串。
PHP Code: PHP代码:
$n = 10;
$all_titles = array();
while($row = mysqli_fetch_array($result)) {
$title = trim($row['Job Title']);
if(array_key_exists($title, $all_titles)) {
++$all_titles[$title];
} else {
$all_titles[$title] = 1;
}
}
arsort($all_titles);
$top_titles = array_slice($all_titles, 0, $n);
$title_list = array();
foreach (array_values($top_titles) as $key => $val) {
array_push($title_list, array_keys($top_titles)[$key]);
}
echo json_encode($title_list);
These array operations seem to be working so far, based on other tests I've done, so I'm pretty sure that $title_list is an array. 根据我所做的其他测试,到目前为止,这些数组操作似乎可以正常运行,因此,我很确定$ title_list是一个数组。
Here is my JS: 这是我的JS:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert("Generated URL: " + URL_gen(xmlhttp.responseText));
}
}
And finally where the problem arises: 最后出现问题的地方:
function URL_gen(list) {
var url = list[2];
return url;
}
I have varied the number in list[#] (list[0], list[1], etc.) and each one is a character, meaning list (which is passed in from onreadystatechange as the responsetext from the PHP function above) is a string, not a JSON array. 我已经更改了list [#]中的数字(list [0],list [1]等),每个数字都是一个字符,这意味着列表(从onreadystatechange传递为上述PHP函数的响应文本)是字符串,而不是JSON数组。
Any suggestions? 有什么建议么?
That's what it does. 这就是它的作用。 Returns a string. 返回一个字符串。 You need to parse it on the client side. 您需要在客户端解析它。
alert("Generated URL: " + URL_gen(JSON.parse(xmlhttp.responseText)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.