[英]how to parse following JSON data using Jquery
我是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 ...]
]
我该如何解析?
您必须将请求的数据类型设置为“ 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
}
});
使用此jQuery方法解析JSON对象。
如果服务器输出实际的JSON(问题中的示例有错误)并且具有正确的内容类型( application/json
而不是PHP默认为text/html
),则您无需执行任何操作。
jQuery将为您解析它(并在成功处理程序中为您提供一个JavaScript对象)。
那不是 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);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.