我正在用php開發數據庫搜索應用程序,並在一個頁面上通過Jquery Ajax(JSON)根據某個參數在數據庫中搜索寄存器,向服務器端腳本發出請求。搜索成功後,我回顯一個關聯數組,其中包含所有編碼爲JSON的條目。索引數組產生格式不正確的JSON
有了Chrome的元件檢查器中,可以閱讀響應,該響應是這樣的:
[0: False
1: "{"id":"5","nome":"Maria","sobrenome":"Joaquina","sexo":"F","rua":"","complemento":"","numero":"0","bairro":"Aeroporto\r\n","telefone":"","email":"","nacionalidade":"Peruano"}"]
元素索引1似乎是良好形成JSON,但我不能從中讀取,任何東西,例如數據[1] .nome返回undefined。
我想知道我的json發生了什麼,我該如何解決這個問題,以便我可以通過它們的屬性訪問這些對象。以下是處理JSON的代碼。
使用Javascript:
$(document).ready(function(){
$('#btnEnviarBairro').click(function(){
var data = $("#bairros_juizdefora").val();
$.ajax({
type: "POST",
url: "processaBuscaId.php",
dataType: 'json',
data: {id : data, type: 1},
success: function(response){
var table = $('<table/>');
for (var i = 1; i < response.length; i++){
table.append("<tr><td>"+response[i].nome+"</tr></td>");
}
$('#receptorBairro').append(table);
},
error: function(xhr, status, error){
console.log(xhr+" "+status+" "+error);
}
}).done(function(){
});
});});
控制器文件的種類:
function buscaBairro($id, $connection) {
$dao = new estrangeiroDao ($connection);
return $dao->selectbyBairroId ($id);
};
echo json_encode (buscaBairro($selectId, $connection));
DAO用於搜索:
function selectbyBairroId($id) {
$sql = 'select * from dados_estrangeiro, nacionalidade, bairros_juizdefora where bairroid = '.$id.' and idnac=idnacionalidade and idbairros_juizdefora = '.$id;
$arres = array();
$result = $this->con->query ($sql);
while ($obj = $result->fetch_object()) {
$estrangeiro = $this->objectToEstrangeiro ($obj);
array_push ($arres, json_encode($estrangeiro->returnAsAssoc()));
}
return $arres;
}
}
ObjectToEstrangeiro方法(上文所用):
function objectToEstrangeiro($obj) {
$est = new estrangeiros ($obj->idestrangeiro, $obj->pnome, $obj->snome, $obj->sexo, $obj->rua, $obj->complemento, $obj->numero, utf8_encode ($obj->nomebairros_juizdefora), $obj->telefone, $obj->email, utf8_encode ($obj->nomenacionalidade));
return $est;
}
「豆」(我知道這是java的東西,但我learnd和tryed在PHP來實現)爲Estrangeiro表:
class estrangeiros {
[...]
[... Attributes and Getters and Setters (I dont know if they are usfull in PHP...]
[...]
public function returnAsAssoc(){
$arres= array("id"=>$this->getId(), "nome" => $this->getNome(), "sobrenome"=>$this->getSobrenome(), "sexo"=>$this->getSexo(),
"rua"=>$this->getRua(), "complemento"=>$this->getComplemento(), "numero"=>$this->getNumero(), "bairro"=>$this->getBairro(),
"telefone" =>$this->getTelefone(), "email"=> $this->getEmail(), "nacionalidade"=>$this->getNacionalidade()
);
return $arres;
}
}
編輯:
由於從評論,我可以看到響應格式不正確的JSON,但現在我試圖找出原因。
這裏有一些事情我發現:
我通過編碼關聯數組控制器,在那裏它再次JSON編碼和呼應JSON的陣列。 如果刪除了任何json編碼,我在Jquery中得不到回覆。
此外,我不能編碼的對象數組,右(至少不具有私有屬性)?所以我必須將我要獲取的對象轉換爲關聯數組,然後將它們存儲在另一個數組中,以便可以訪問它們的值。
使用'jsonlint.org'你的JSON看起來是'Badly Formed'但是如果你從前面刪除'[0:False1:'''''從結尾它確實有效 – RiggsFolly
任何提示爲什麼?它似乎在索引之後形成良好。如果格式錯誤,它是如何發送的? –