dongxuxian1123
2017-12-20 04:51
浏览 704

JSON响应返回undefined

First use 'json_decode' to convert array to JSON response

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

echo json_encode( $test );

and then process the JSON response in the front-end side.

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

but unfortunately it returns 'undefined'

enter image description here

A view of the response using a JSON editor

enter image description here

I can do this

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

which surely returns the data that I want but I prefer not to do a second loop.

any idea, help please?

图片转代码服务由CSDN问答提供 功能建议

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

  $ test = [“connections”=>  [[“title”=>  “连接1”,“日期”=>  “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'

< / p>

使用JSON编辑器的响应视图

我可以这样做

  $。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条回答 默认 最新

  • dongni8969 2017-12-20 05:09
    已采纳

    Try this. I'm sure you have no header('Content-type:application/json') in you PHP if I'm not mistaken. If you don't have, It will return as a string. You need to parse it by using $.parseJSON of jQuery built in method

    $.get('http://cnbusiness.nextdayhost.com/ajax/get_business_connections', function(e) {
      $.each($.parseJSON(e),function(i,e){
        // code here ...
      });
    });
    
    打赏 评论
  • dongyiyu3953 2017-12-20 05:00

    parse output to json, plus, because e.connection was an array, enter image description here

    if you want to get title from connection you can do like

    e = JSON.parse(e)
    console.log(e.connections[0].title)
    
    打赏 评论

相关推荐 更多相似问题