通过php返回多个json


returning multiple json via php

我需要从数据库中检索一个可以具有相同名称的用户列表。我很难将查询结果转换为json。

如果我只检索一个结果,代码就会工作,但由于我开始使用LIKE,它开始失败。

php代码:

<?php

$q = $_POST['q'];
require('connect.php');
$i = 0;
$sql="SELECT `_nome`, `_endereco`, `_telefone`, `_imgstring`, `_dtAcesso`, `_descricao`, `_fkIdUser` FROM `tbvisitantes` WHERE _nome LIKE CONCAT ('%',?,'%')";
$stmt= $conn->prepare($sql);
$stmt->bind_param('s', $q);

if ($stmt){
$stmt->execute();
$stmt->bind_result($rName, $rEndereco, $rTelefone, $rImgString, $rDtAcesso, $rDescricao, $rFkIdUser);
while ($row = $stmt->fetch_array()){
$json_output = array('name' => $rName, 'address' => $rEndereco, 'tel' => $rTelefone, 'imgString' => $rImgString, 'dtAcesso' => $rDtAcesso, 'descricao' => $rDescricao, 'fkIdUser' => $rFkIdUser);
echo json_encode($json_output);
}
$stmt->close();
}
mysqli_close($conn);
?>

接收结果的脚本:

$.ajax({
url: 'getuser.php',
type: 'POST',
data: {q: str},
success: function(jsonString){
$vIndex = '<input class="vInput"></input>';
$($cadContent).appendTo('#cadContent');
var json = $.parseJSON(jsonString);
var jsonLenght = Object.keys(jsonString).length;

$.each(json, function(index, el) {
$($vIndex).attr('id', index).val(el).appendTo('#txtHint');

});

}
})
.done(function() {
console.log("success");
})
.fail(function(xhr) {
alert("An error ocurred:" + xhr.status + xhr.statusText);
console.log('failed');
})
.always(function() {
console.log("complete");
});

}

我认为我的问题可能出现在JSON的构建中,但我现在不知道如何解决它。

您不能在json中回显多个响应。您必须将响应组合成一个数组,然后必须回显响应。

,下面的片段将对您有所帮助

服务器页面:

while ($row = $stmt->fetch_array()){
   $json_output[] = array('name' => $rName, 'address' => $rEndereco, 'tel' => $rTelefone, 'imgString' => $rImgString, 'dtAcesso' => $rDtAcesso, 'descricao' => $rDescricao, 'fkIdUser' => $rFkIdUser);
}
echo json_encode($json_output);

在Ajax页面中:

// your success callback handler
function handler( response ) {
  // execute code for object 1
  doStuff(response[0] );
  // execute code for object 2
  doOtherStuff( response[1] );
}

您需要将行组合成一个JSON数组:

if ($stmt){
  $stmt->execute();
  $stmt->bind_result($rName, $rEndereco, $rTelefone, $rImgString, $rDtAcesso, $rDescricao, $rFkIdUser);
  $rows = array();
  while ($row = $stmt->fetch_array()){
    $json_output = array('name' => $rName, 'address' => $rEndereco, 'tel' => $rTelefone, 'imgString' => $rImgString, 'dtAcesso' => $rDtAcesso, 'descricao' => $rDescricao, 'fkIdUser' => $rFkIdUser);
    $rows[] = $json_output;
  }
  echo json_encode($rows);
}