【问题标题】:jQuery Ajax JSON Return Single Variable Plus Multidimensional ArrayjQuery Ajax JSON 返回单变量加多维数组
【发布时间】:2018-04-03 00:28:18
【问题描述】:

注意:这个问题已经被否决了 3 次,但没有人提供被否决的理由。这对任何人都没有帮助 社区。不要让这阻止您通过以下方式获得出色的答案 Anurag 和 Phil,如下所示。

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

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

基本上查询后,我的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);
   }
});

【问题讨论】:

  • $ProgRow["ProgCode"]; 你必须用引号括起来keys
  • 对于一个与问题无关的例子的相当小的批评。是你把我降级的人吗?
  • 解决方案并不复杂......总是发送一个数组并检查它的长度。对于没有结果发送空数组
  • 首先我没有降级你(如果你指的是我),我的评论不是批评(如果你也指我的话)。我只是想指出你可能错过的东西,所以也许你可以从那开始。
  • 当#rows > 1 时,您没有创建关联数组,因此也不要为其他条件创建关联数组

标签: php jquery json ajax


【解决方案1】:

如果不确定这是否是您想要的,但据我了解,您希望在 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
  }
}

【讨论】:

  • 使用 var stuff = json.parse(data);控制台.日志(东西);出于某种原因,给了我一个“未定义 json”。有什么想法吗?
  • 使用JSON 而不是json
  • 使用dataType: jsondata 将已经被解析。不需要再次解析
  • 很高兴知道,因为我在尝试使用它时遇到语法错误,而且数据对我来说似乎没问题。
  • 哦,我猜这是一个 jquery 的东西。我错过了。
【解决方案2】:

正如 cmets 中提到的,只返回一个结果数组,不管有多少。这使您的 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 => ...)

【讨论】:

  • 啊-我试图弄清楚如何获得多维的长度,但是正如您在案例结构中指出的那样,这确实没有必要。似乎无论有多少嵌套,长度都应该返回顶部数组的数量,但是,除非我在某个地方搞砸了,否则它似乎没有。我喜欢这个。
  • 我接受了 Anurag 的回答,因为在我看到你的回答之前我已经让它工作了,而且在尝试你的回答时,我遇到了 JavaScript 长度函数的问题。不知道为什么。不过,这看起来像是一些非常有效的代码,所以我将继续尝试找出我做错了什么。
  • 根本不懂data.length问题。在 1 条记录(22 个字段)响应中,它显示的长度为 512。这可能是也可能不是字符数。不过数据很好。
  • @RationalRabbit 您是否将header('Content-type: application/json') 部分添加到您的PHP 中? 512 可能是 JSON 字符串的长度。你得到一个字符串是因为 jQuery 不知道它是 JSON
猜你喜欢
  • 1970-01-01
  • 2013-10-22
  • 2014-10-20
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
相关资源
最近更新 更多