2012-05-30 64 views
0

在我的Ajax代碼:約json_encode和Ajax數據類型: 「JSON」

$.ajax({ 
     url: CI_ROOT + "isUserExist", 
     type: "GET", 
     data: {recepient: recepient}, 
     success: function(r) { 
      console.log(r) 
     } 
}) 

給了我一個輸出[{ 「記錄」: 「1」}] [{ 「記錄」: 「1」} ]因此,我通過在我的ajax代碼中添加dataType:「json」來將它解析爲json。但是當我解析它時,它不會給我輸出,但在try-catch-block上出錯。

如何讓它顯示爲對象? 在我的PHP代碼中,我做這種方式:

for ($i = 0; $i < count($matches[0]); $i++) { 
    echo json_encode($this->searchmodel->doesUsersExists($matches[0][$i])); 
} //gets the user id of the user from a given string. 

回答

2

這不是有效的JSON。根據你現有的結果做一個數組並編碼

5

將每個條目添加到一個數組,然後json對該數組進行編碼,而不是分別對每個數組進行編碼。如果您只有一個電話給json_encode,您將獲得有效的JSON:

$result = array(); 
for ($i = 0; $i < count($matches[0]); $i++) { 
    $result[] = $this->searchmodel->doesUsersExists($matches[0][$i]); 
} //gets the user id of the user from a given string. 

echo json_encode($result);