从php返回json并处理

时间:2013-09-20 18:26:53

标签: php jquery json

我从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>

这是我从start.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,这就是问题所在。所以我添加了另一个数组并在文件末尾使用了echo json_decode($ array,true)。为了以防万一,可能会帮助某人。

干杯

4 个答案:

答案 0 :(得分:0)

首先,在您的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回调函数中使用。

希望这有帮助!

答案 1 :(得分:0)

首先,您应该在服务器脚本中使用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));

进行验证

答案 2 :(得分:0)

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

然后解析数据,

 data = $.parseJSON(data);

然后阅读var id = data.id;

另外,在PHP中,不需要使用print_r()。只需使用echo而不是print_r()。就像:

echo json_encode($return);

答案 3 :(得分:-1)

您需要将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还有一个用于获取名为getJSON()的JSON的内置函数。如果内存服务,这只是进行.ajax()调用并指定json数据类型的简写。这将为您处理上述(解析JSON),并且是推荐的解决方案。