简体   繁体   English

如何使用jQuery解析以下JSON数据

[英]how to parse following JSON data using Jquery

I am new on JQuery. 我是JQuery新手。 I have this JSON response from the server how could I parse it? 我从服务器收到此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 ...]
]

How could I parse this? 我该如何解析?

You have to set the data type of the request to "json", and the data will be already parsed in your success callback. 您必须将请求的数据类型设置为“ json”,并且数据将已经在成功回调中进行了解析。

Everything you need to know at the moment is on http://api.jquery.com/jQuery.ajax/ 您目前需要了解的所有信息都在http://api.jquery.com/jQuery.ajax/上

Here is a very simple example of what you can do: 这是您可以做什么的非常简单的示例:

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

jQuery.parseJSON jQuery.parseJSON

Use this jQuery method to parse JSON objects. 使用此jQuery方法解析JSON对象。

If the server outputs actual JSON (the example in the question has errors) and it has the correct content type ( application/json rather then the text/html that PHP defaults to) then you don't need to do anything. 如果服务器输出实际的JSON(问题中的示例有错误)并且具有正确的内容类型( application/json而不是PHP默认为text/html ),则您无需执行任何操作。

jQuery will parse it for you (and present you with a JavaScript object in the success handler). jQuery将为您解析它(并在成功处理程序中为您提供一个JavaScript对象)。

That's not JSON. 不是 JSON。 What you have posted looks like a PHP array that had brackets wrapped around it to try to make it into JSON. 您发布的内容看起来像一个PHP数组,其周围带有方括号,以尝试使其变为JSON。

Use this site to validate your JSON in the future. 将来使用此站点来验证您的JSON。

Now, to get your PHP array into JSON, use json_encode() and dispatch it to the browser with a specific header. 现在,要将您的PHP数组转换为JSON,请使用json_encode()并将其分派给具有特定标头的浏览器。

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

Now, you'll have actual JSON with which you can use in JavaScript. 现在,您将拥有可以在JavaScript中使用的实际JSON。

$.get(  'yourFile.php',
        function(data){
            console.log(data);
        }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM