php json_encode 不会产生真实对象/将数组字符串转换为真实对象/将 php 数组转换为 json

发布于 2024-10-04 08:20:49 字数 674 浏览 6 评论 0原文

这是我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

罗罗贝儿 2024-10-11 08:20:49

我看到您正在使用 jquery,如果您希望数据作为 json 对象返回给您,您需要执行两件事中的一件。

  1. 将 header("Content-Type: application/json") 添加到您的 php 文件中,这将告诉 jquery 将其转换为 json 对象而不是文本

  2. 向 $.post 添加第四个参数,

$.post('/ajax-database.php', function (data) {
    console.log($.parseJSON(data));
    $.each(data, function (key, value) {
        console.log(value);
    });
}, "json");

如果它不是 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.

  1. 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

  2. Add a forth parameter to your $.post,

$.post('/ajax-database.php', function (data) {
    console.log($.parseJSON(data));
    $.each(data, function (key, value) {
        console.log(value);
    });
}, "json");

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.

烟若柳尘 2024-10-11 08:20:49

JSON 字符串。如果您希望能够迭代它,那么您需要对其进行解码。

JSON is strings. If you want to be able to iterate over it then you need to decode it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文