簡體   English   中英

JSON響應返回未定義

[英]JSON response returns undefined

首先使用'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”

在此處輸入圖片說明

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

它肯定會返回我想要的數據,但我不希望進行第二次循環。

任何想法,請幫忙嗎?

嘗試這個。 如果我沒記錯的話,我確定您的PHP沒有header('Content-type:application/json') 如果沒有,它將作為string返回。 您需要使用jQuery內置method $.parseJSON進行解析

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

將輸出解析為json,再加上,因為e.connection是一個數組, 在此處輸入圖片說明

如果您想從連接中獲取標題,可以這樣做

e = JSON.parse(e)
console.log(e.connections[0].title)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM