【问题标题】:Error printing Ajax data to html table将 Ajax 数据打印到 html 表时出错
【发布时间】:2017-02-23 10:29:43
【问题描述】:

我有一个 php 函数来生成数字列表,以及一个 ajax 调用来检索该数字数组。我可以提醒列表并且它工作正常,但是当我尝试将其打印到 HTML 表中时,我收到错误“未捕获的 TypeError:无法使用 'in' 运算符在 Infinity 中搜索 'length'” 任何帮助将不胜感激。

<!DOCTYPE html>
<html>
<head>
<script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax({
type: "POST",
url: "primeNumbers.php",
datatype: 'JSON',
success: function(data){
    var d = $.each(JSON.parse(data));
    var output;
    $.each(d,function(i,e){
        output += '<tr><td>'+e.data+'</tr></td>';
        });

    $('#table').append(output);

    alert(data);
}
});
</script>
<h1>Heading</h1>
<table id="table">
  <tr>
    <td>Name</td>
  </tr>
</table>

</body>
</html>

primeNumbers.php

<?php
function prima($n){

  for($i=1;$i<=$n;$i++){

          $counter = 0; 
          for($j=1;$j<=$i;$j++){ 


                if($i % $j==0){ 

                      $counter++;
                }
          }


        if($counter==2){

               echo json_encode($i);
        }

    }
} 
prima(100);  

?>

【问题讨论】:

  • 你看过你的 php 脚本的输出了吗?它只是输出一个非常大的数字。您必须将素数放入 php 脚本中的数组中,然后输出该数组的 json 版本。
  • 顺便说一句:这是一种非常低效的计算素数的方法

标签: php ajax


【解决方案1】:

实际错误意味着 $.each 可能获取了错误的数据类型。例如。一个字符串 when in 应该被传递一个它可以迭代的对象。在您的情况下,javascript 和 PHP 代码都有一些错误。您的 PHP 代码只是回显了质数。所以你的 ajax 函数得到了一个连接的数字字符串(你的 Uncaught TypeError 的原因)。您必须将数字推送到数组,将其转换为 json 字符串并返回该结果,这样您就可以在需要的任何地方回显它。

仅关于您的 ajax 函数。在变量声明中松开 $.each()。 所以:

var d = $.each(JSON.parse(data));

变成:

var d = JSON.parse(data);

更新添加了 PHP 修复

这是固定/重构的 PHP 函数。

function prima($n){

   $res = []; // Initiate result array

   for($i=1;$i<=$n;$i++){

      $counter = 0; 
      for($j=1;$j<=$i;$j++){ 


            if($i % $j==0){ 

                  $counter++;
            }
      }


    if($counter==2){
         $res[] = $i; // store value to array
    }

  }

  return json_encode($res); // return converted json object

}

header('Content-Type: application/json'); // tell browser what to expect
echo prima(100); // echo the json string returned from function

【讨论】:

  • 是的,我已经尝试过了。我似乎无法克服错误
  • @user2168066 更新了答案以包含您的固定功能
猜你喜欢
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
相关资源
最近更新 更多