php json_encode 不会产生真实对象/将数组字符串转换为真实对象/将 php 数组转换为 json
这是我的 PHP 代码,它从 mongodb 获取集合列表,
$list = $db->dbname->listCollections();
$result = array();
$i=0;
foreach ($list as $thiscollection) {
$result[$i++] = $thiscollection->getName();
}
echo json_encode( $result );
我在回调中执行 console.log ,这就是我所看到的。
["fruits", "dogs", "cars", "countries"]
问题是这是一个字符串,而不是一个数组。我需要迭代这些值。我如何将其变成一个真实的对象,或者让 php 给我 json 而不是 php 数组,以便我可以在其上使用 parseJSON 。
谢谢。
js:
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
});
Here is my PHP code, it's getting a listing of collections from mongodb
$list = $db->dbname->listCollections();
$result = array();
$i=0;
foreach ($list as $thiscollection) {
$result[$i++] = $thiscollection->getName();
}
echo json_encode( $result );
I do console.log in the callback and this is what I see.
["fruits", "dogs", "cars", "countries"]
The problem is that this is a string, not an array. I need to iterate through these values. How an I make this into a real object or get php to give me json rather than php array so I can use parseJSON on it.
Thanks.
js:
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我看到您正在使用 jquery,如果您希望数据作为 json 对象返回给您,您需要执行两件事中的一件。
将 header("Content-Type: application/json") 添加到您的 php 文件中,这将告诉 jquery 将其转换为 json 对象而不是文本
向 $.post 添加第四个参数,
如果它不是 json,这将告诉 jquery 调用你的错误处理程序,就像你的 php 代码失败并输出 html 一样。你真的应该使用 $.ajax,我不知道为什么有人使用 $.post,你不能做任何有意义的错误处理。
I see you are using jquery, if you want data to come back to you as a json object you need to do 1 of 2 things.
add header("Content-Type: application/json") to your php file, this will tell jquery to convert it to a json object instead of as text
Add a forth parameter to your $.post,
that will tell jquery to call your error handler if its NOT json, like if your php code fails and outputs html instead. You really should use $.ajax, i have no idea why anyone uses $.post, you can't do ANY meaningful error handling.
JSON 是字符串。如果您希望能够迭代它,那么您需要对其进行解码。
JSON is strings. If you want to be able to iterate over it then you need to decode it.