从 PHP 返回 JSON 和句柄


return json from php and handle

我从ajax调用中得到这个

{"id":"381120774951940096","time":"Posted 0 minutes and 51 seconds ago.",....

如何将这些添加到变量、id、时间等中? data.id 行不通,它说不定。

<script>
$(function() {
        $.ajax({
            type: "POST",
            url: "start.php",
            cache: false,
            success: function(data) {
                console.log(data.name);
                console.log(data);
            }
        })
    });
</script>

这就是我从头开始返回的内容.php

$return = array('id' => $info['id_str'] ,'time' => timeDiff(new DateTime($info['created_at'])), 'name' => $info['user']['name'], 'text' => $info['text'], 'image' => $picture, 'url' => "http://twitter.com/{$info['user']['screen_name']}");
print_r(json_encode($return));

编辑我在foreach循环中print_r了那个,这就是问题所在。所以我添加了另一个数组并在文件末尾使用了回显json_decode($array,true)。写这个以防万一,可能会帮助某人。

干杯

首先,在 PHP 中,将行更改为:

echo json_encode($return, true);

第二个参数可确保 JSON 可解释为关联数组。此外,在返回 JSON 时,您应该使用 echo 而不是 print_r; print_r可以更改格式。

接下来,使用以下 AJAX 调用:

$.ajax({
    type: "POST",
    url: "start.php",
    dataType: "json", // Add this option.
    cache: false,
    success: function(data) {
        console.log(data.name);
        console.log(data);
    }
})

dataType: "json"选项可确保data在检索后立即解析为 JSON 对象。因此,data.id应该立即在success回调函数中可用。

希望这有帮助!

首先,您应该在服务器脚本中使用echoprint_r主要用于调试数组。

其次,您应该为 ajax 调用声明一个dataType选项:

$.ajax({
    dataType: "json", // <-- here
    type: "POST",
    url: "start.php",
    cache: false,
    success: function(data) {
        console.log(data.name);
        console.log(data);
    }
});

现在拥有它的方式,我认为你正在得到一个字符串响应作为数据。

您可以使用console.log(JSON.stringify(data));进行验证

你必须

在ajax中设置dataType: 'json'。这意味着jQuery会将结果解析为JSON。

然后解析数据,

 data = $.parseJSON(data);

然后阅读var id = data.id;

另外,在你的PHP中,不需要使用print_r()。只需使用 echo 代替 print_r().like:

echo json_encode($return);
您需要

将 JSON 字符串解析为对象。您可以使用 JSON.parse 来执行此操作。

// Your JSON string
var json_str = "{'id': 'foo', 'time': 'bar'}";
// We need to parse it, converting it into a JS object
var json_obj = JSON.parse(json_str);
// We can now interact with it
console.log(json_obj.id);
console.log(json_obj.time);

或者,您可以使用内置的 jQuery 函数 parseJSON() 解析 JSON。

jQuery还有一个内置的函数,用于获取JSON,称为getJSON()。如果没记错的话,这只是执行.ajax()调用和指定数据类型的简写 json .这将为您处理上述(解析 JSON),并且是推荐的解决方案。