JSON响应返回undefined

时间:2017-12-20 04:51:51

标签: php jquery json ajax

首先使用' json_decode'将数组转换为JSON响应

$test = [ "connections" => [ [  "title" => "Connection 1", "date"  => "01-26-2010", "id" => "1" ] ] ];

echo json_encode( $test );

然后在前端处理JSON响应。

$.get( 'http://cnbusiness.nextdayhost.com/ajax/get_business_connections', function(e){
   console.log( e.connections );
});

但不幸的是,它返回了未定义的

enter image description here

使用JSON编辑器的响应视图

enter image description here

我可以这样做

$.get( 'http://cnbusiness.nextdayhost.com/ajax/get_business_connections', function(e){
  $.each(JSON.parse(e),function(i,e){
    $.each(e,function(i,e){
        console.log(e.title);
    });
  });
});

肯定会返回我想要的数据,但我不想再进行第二次循环。

任何想法,请帮忙吗?

2 个答案:

答案 0 :(得分:0)

试试这个。如果我没有弄错的话,我确定你header('Content-type:application/json')中没有PHP。如果您没有,它将以string返回。您需要使用$.parseJSON jQuery内置method

来解析它
$.get('http://cnbusiness.nextdayhost.com/ajax/get_business_connections', function(e) {
  $.each($.parseJSON(e),function(i,e){
    // code here ...
  });
});

答案 1 :(得分:-1)

将输出解析为json,另外,因为e.connection是一个数组, enter image description here

如果你想从连接获得标题,你可以这样做

e = JSON.parse(e)
console.log(e.connections[0].title)
相关问题