php json_encode doesn't result in real object / make array string into real object / turn php array into json

谁说我不能喝 提交于 2019-12-24 12:16:16

问题


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);
    });
});

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4293295/php-json-encode-doesnt-result-in-real-object-make-array-string-into-real-obje

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!