更新:请参阅 Anthony Grist 对您的问题的评论,我错过了您的 JSON 无效的事实。由于他没有发布答案,我会去接它。
您的JSON无效,因为您要返回两个单独的数组,这是一个:
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
和这个:
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
你不能这样做,因为 JSON 文档的顶层必须是一个东西(一个对象或一个数组)。
您可以返回一个包含每个数组属性的对象:
{
"vdata":
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
"datedata":
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
}
解析后(见下文),您可以像这样访问该数据:
console.log(data.vdata[0].v); // "233"
console.log(data.datedata[0].date); // "2013-02-01"
或者一个有两个插槽的数组,每个插槽中都有一个数组:
[
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
]
解析后(见下文),您可以像这样访问该数据:
console.log(data[0][0].v); // "233"
console.log(data[1][0].date); // "2013-02-01"
就个人而言,我更喜欢使用对象,因为从那时起我就很清楚我正在访问哪个数组。
原答案:
jQuery 会将 JSON 解析为您的对象并将其传递给success
函数,然后您可以像访问任何其他对象一样访问该函数。在您的情况下,顶层是一个数组。所以:
$.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false,
success: function(data) {
// Use the line from above that suits the way
// you updated your JSON structure
}
});
旁注:async: false
已弃用,将在某个时候删除。做同步 ajax 请求通常不是一个好主意,它往往会在请求期间锁定浏览器的 UI。success
相反,只需构建代码以在触发回调时继续处理。