jQuery Ajax JSON返回单变量加多维数组

时间:2018-04-03 00:28:18

标签: php jquery json ajax

  

注意:这个问题现在已经三次投票,但是没有人提供投票的原因。这对任何人都没有帮助   社区。不要让那阻止你从伟大的答案   Anurag和Phil都在下面。

我正在使用Ajax,json检索数据。数据库可能不返回任何结果,一条记录或多条记录。我需要知道收到数据时的行数。如果只有一行,它只会填写表格。如果有多行,则会将用户定向到列表以进行选择。

为了更详细地解释,行数存储在PHP文件的$ Rows变量中,该变量来自查询结果,无需显示。有一个查询,这是它之后的代码。所以,换句话说,我需要知道的是,如何将$ Rows变量与多维数组一起发送回jQuery函数。如果仍然无法理解,请参阅这些特定部分的评论。

基本上,在查询之后,我的PHP看起来像这样:

$Rows = mysql_num_rows($Result);
if($Rows == 1)
{
    $P = mysql_fetch_assoc($Result);
    $Output = json_encode($P);
}
elseif($Rows > 1)
{
    $x = 0;
    while($ProgRow = mysql_fetch_array($Result))
    {
        // Of course, I could add the $Row var here, but I would need
        // To add it to each row, which seems a little daffy
        $P[$x]['ID'] = $ProgRow['ID'];
        $P[$x]['ProgCode'] = $ProgRow['ProgCode'];
        $P[$x]['ProgName'] = $ProgRow['ProgName'];
        $x++;
    }
    $Output = json_encode($P);
}
else
{
    $P = json_encode(0);
    $Output = $P;
}
echo($Output);

这是jQuery:

$.ajax(
{
   type: 'POST',
   url: 'scripts/UtilAjax.php',
   data: 'Sec=EditPrograms',
   dataType: 'json',
   success: function(data,status)
   {
      // ideally what needs to happen here is to be able to
      // return the $Rows variable as well, to determine how
      // To deal with the return data.
      console.log(status);
      console.log(data.ID+' '+data.ProgCode+' '+data.ProgName);
   }
});

2 个答案:

答案 0 :(得分:2)

如果我不确定这是否是您想要的,但根据我的理解,您希望在ajax中获取$row数据和$output数据。在这种情况下,只需在json编码的关联数组中发回两个。

echo json_encode([$rows, $Output]);

最后,在客户端,

success: function(data, status) {
  console.log("Output: " + data.Output.ID + ' ' + data.Output.ProgCode + ' ' + data.Output.ProgName);
  if (data.rows == 0) {
    // do something ...
  } else if (data.rows == 1) {
    // populate the form
    console.log(data.output.ID + ' ' + data.output.ProgCode + ' ' + data.output.ProgName);
  } else {
    // multiple rows
    // display the select list
  }
}

答案 1 :(得分:1)

正如评论中所提到的,只要返回一系列结果,无论多少。这使您的API保持一致并减少代码。

例如

$out = []; // start with an empty array
while($ProgRow = mysql_fetch_array($Result)) {
    $out[] = $ProgRow; // push onto the array
}
header('Content-type: application/json');
echo json_encode($out);
exit;

现在,您的结果将始终是包含零个或多个记录的数组。然后你的JS可以简单地检查长度以确定有多少结果

$.post('scripts/UtilAjax.php', {
  Sec: 'EditPrograms'
}).then(data => {
  console.log('Number of results:', data.length)
  switch(data.length) {
    case 0:
      // handle no records
      break;
    case 1:
      fillOutForm(data[0]) // use the first record
      break;
    default:
      showList(data)
  }
})

为了让jQuery知道响应是JSON,你应该添加正确的Content-type响应头(如上所述),或强制通过

解析响应
$.post('scripts/UtilAjax.php', {
   Sec: 'EditPrograms'
}, null, 'json').then(data => ...)

$.ajax({
  url: 'scripts/UtilAjax.php',
  method: 'POST',
  data: {Sec: 'EditPrograms'},
  dataType: 'json'
}).then(data => ...)