我已向我的服务器请求用户提交的帖子列表。但作为响应,我得到一个包含 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);
}
});
关于javascript - ajax 响应的访问元素以数组字符串的形式出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34543887/