JSON响应返回undefined

问题描述 投票:1回答:2

首先使用'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 );
});

但不幸的是它返回'undefined'

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);
    });
  });
});

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

任何想法,请帮忙吗?

php jquery json ajax
2个回答
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
投票

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

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

e = JSON.parse(e)
console.log(e.connections[0].title)
© www.soinside.com 2019 - 2024. All rights reserved.