0

我是 JQuery 的新手。我有来自服务器的这个 JSON 响应,我该如何解析它?

[
    {
        "note": {
            "created_at": "2012-04-28T09:41:37Z",
            "updated_at": "2012-04-28T09:41:37Z",
            "text": "aaaaaaaaaaafdafasd fasfasd dfa sdfasf asdfa fasdfda",
            "lng": 44.5159794497071,
            "id": 7,
            "deleted": false,
            "user_id": 1,
            "note_type": "text",
            "lat": 40.1884140543842
        }
    },
    [ ... more JSON ...]
]

我怎么能解析这个?

4

4 回答 4

3

您必须将请求的数据类型设置为“json”,并且数据将已经在您的成功回调中解析。

你现在需要知道的一切都在http://api.jquery.com/jQuery.ajax/

这是一个非常简单的示例,说明您可以做什么:

$.ajax({
    url: url, // the service URL. Must answer proper JSON
    data: {  // the parameters of the request. This should be adapted to your case
        param1: value1,
        param2: value2
    },
    dataType: "json",
    type: "POST",
    success: function(resultData) {
        // here, resultData is your parsed json
    },
    error: function() {
        // handle error here
    }
});
于 2012-05-31T12:43:46.007 回答
1

jQuery.parseJSON

使用这个 jQuery 方法来解析 JSON 对象。

于 2012-05-31T12:44:52.160 回答
0

如果服务器输出实际的 JSON(问题中的示例有错误)并且它具有正确的内容类型(application/json而不是text/htmlPHP 默认的),那么您不需要做任何事情。

jQuery 将为您解析它(并在成功处理程序中为您提供一个 JavaScript 对象)。

于 2012-05-31T12:48:22.607 回答
0

不是JSON。您发布的内容看起来像一个 PHP 数组,其中包含括号以尝试将其转换为 JSON。

将来使用此站点验证您的 JSON。

现在,要将您的 PHP 数组转换为 JSON,请使用json_encode()它并将其发送到带有特定标头的浏览器。

$array = array( 'test' => 'sure' );
header('Content-type: application/json');
print json_encode($array);
exit;

现在,您将拥有可以在 JavaScript 中使用的实际 JSON。

$.get(  'yourFile.php',
        function(data){
            console.log(data);
        }
);
于 2012-05-31T12:49:56.973 回答