我已经向服务器请求了用户提交的帖子列表。但作为回应,我得到了一个包含stdClass对象数组的字符串。如果它是实际的数组,就不会有问题。但这是一种刺痛。如下所示:
" array(
[0]=>stdClass('title'='title of post','post_id'=4),
[1]=>stdClass('title'='title of post','post_id'=4)
)"
typeof(response)
给了我"字符串"。我的问题是,如何从中访问单个元素?代码:
$.ajax('../includes/ajaxpostinfo.php',{
data:data,
type:"POST",
success:function(response){
alert(typeof(response)); // it prints out "string"
},
error:function(response){
alert(response);
}
});
做一些类似的事情:
服务器:
$array= array(
[0]=>stdClass('title'='title of post','post_id'=4),
[1]=>stdClass('title'='title of post','post_id'=4)
);
echo json_encode($array);
客户:
$.ajax('../includes/ajaxpostinfo.php',{
data:data,
type:"POST",
dataType : "json",//set data type
success:function(response){
alert(typeof(response));
},
error:function(response){
alert(response);
}
});
如果添加
dataType : "json"
在您的ajax请求中
"json":将响应求值为json,并返回一个JavaScript对象。跨域"json"请求将转换为"jsonp",除非请求的请求选项中包含jsonp:false。JSON数据以严格的方式进行解析;任何格式错误的JSON都会被拒绝,并引发解析错误。从jQuery 1.9开始,空响应也被拒绝;服务器应该返回null或{}的响应。(有关正确的json格式的更多信息,请参阅json.org。)
JQuery Ajax文档