如何使用jQuery读取JSON文件并将数据保存在变量中?

时间:2011-06-15 06:06:44

标签: javascript jquery json

{
   "code":100,
   "data":{
      "month":[
         {
            "yearText":"2011",
            "months":[
               {
                  "monthText":"6",
                  "days":[
                     {
                        "dayText":"13",
                        "cios":[
                           {
                              "status":"continues",
                              "start":"23:00:00",
                              "end":"23:59:59",
                              "id":12
                           }
                        ],
                        "bois":[
                           {
                              "status":"continues",
                              "start":"23:30:00",
                              "end":"23:59:59",
                              "id":12
                           }
                        ]
                     },
                     {
                        "dayText":"14",
                        "cios":[
                           {
                              "status":"continued",
                              "start":"00:00:00",
                              "end":"01:00:00",
                              "id":12
                           },
                           {
                              "status":"within",
                              "start":"11:42:14",
                              "end":"11:43:45",
                              "id":11
                           }
                        ],
                        "bois":[
                           {
                              "status":"continued",
                              "start":"00:00:00",
                              "end":"00:30:00",
                              "id":12
                           },
                           {
                              "status":"within",
                              "start":"11:42:39",
                              "end":"11:43:33",
                              "id":11
                           }
                        ]
                     }
                  ]
               }
            ]
         }
      ],
      "next":"\/attendance\/get-history\/2011\/07",
      "previous":"\/attendance\/get-history\/2011\/05"
   },
   "msg":"Attendance history of John Doe on June, 2011."
}

我需要读取该文件“attendance.json”并使用jQuery将数据保存为变量。

由于

2 个答案:

答案 0 :(得分:1)

我不完全确定您的意思或为什么您已添加PHP代码,但前提是attendance.json文件与您的JavaScript位于同一个域中(Google“同源政策”) ...

$.getJSON('attendance.json', function(data, textStatus, jqXHR) {
    // data contains your JSON object
    alert(data.code); // 100
});

对于外部数据源(单独的域),仅当远程服务器支持JSONP请求时才可以这样做。

否则,您可以尝试获取数据服务器端(PHP)

$data = json_decode(file_get_contents('http://example.com/attendance.json'));

请参阅http://api.jquery.com/jQuery.getJSON/http://php.net/manual/en/function.json-decode.php

答案 1 :(得分:0)

jQuery有getJSON method

相关问题