javascript - ajax 响应的访问元素以数组字符串的形式出现

标签 javascript php jquery arrays ajax

我已向我的服务器请求用户提交的帖子列表。但作为响应,我得到一个包含 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/

相关文章:

javascript - 使用 PHP 变量打开 Bootstrap 模态框,无需重新加载网站

php - 将mysql数据放入html中存在的div中

javascript - 鼠标悬停事件传播问题 - 手动传播

jQuery toggleClass 在移动设备上无法正常工作

Javascript正则表达式替换 - 不替换所有必需的字符串

javascript - 在 Highcharts.js 中自定义工具提示?

javascript - Backbone.js 自定义构造函数?

javascript - 在 pjax 请求上显示加载文本

php - 在 CakePHP 中从模型获取数据的最有效方法是什么?

jquery - 数据表插件: columnsToggle ignore specific columns