首页 > 解决方案 > 无法从 PHP 到 JS 获得多个回声

问题描述

我正在尝试将所有具有相同名称的行从我的 MySQL 数据库中获取到我的 HTML 表中。所以基本上,我的 php 脚本调用了将getRequestToShow.php值回显到 .js 文件(它通过使用 向 php 脚本询问值XMLHttpRequest)。然后这个 .js 文件添加 HTML 表中的行。

我从 php 中回显 MySQL 行,如下所示:

$conn = new mysqli($servername, $username, $password, $db_name);

if ($conn->connect_error){
  die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$id = mysqli_real_escape_string($conn,$id);
$query = "SELECT * FROM `requests` WHERE `name`='$id'";
$result = mysqli_query($conn,$query);

while($row = mysqli_fetch_array($result)) {
echo json_encode(array('first'=>$row['name'],'second'=>$row['amount'],'third'=>$row['date'],'fourth'=>$row['state']));
}

..但我只能从我的数据库中的值获取到 HTML 表。如果有多个同名的行,它将不会在 HTML 表格上显示任何内容。

function showUser45(str) {
    var tableRef = document.getElementById('customers').getElementsByTagName('tbody')[0];
    var newRow   = tableRef.insertRow(tableRef.rows.length);
    var xmlhttp22 = new XMLHttpRequest();
    xmlhttp22.onreadystatechange = function() {
      if (xmlhttp22.readyState == 4 && xmlhttp22.status == 200) {
          if(xmlhttp22.responseText === "") {
            var newCell  = newRow.insertCell(0);
            var newText  = document.createTextNode("No earlier withdraws");
            newCell.appendChild(newText);  
        } else {
            var h2 = JSON.parse(xmlhttp22.responseText);
            var newCell1  = newRow.insertCell(0);
            var newText1  = document.createTextNode(h2.first); 
            var newCell2  = newRow.insertCell(1);
            var newText2  = document.createTextNode(h2.second); 
            var newCell3  = newRow.insertCell(2);
            var newText3  = document.createTextNode(h2.third); 
            newCell1.appendChild(newText1); 
            newCell2.appendChild(newText2);
            newCell3.appendChild(newText3);
            if (h2.fourth == 1) {
                var newCell4  = newRow.insertCell(3);
                var newText4  = document.createTextNode("Completed"); 
                newCell4.appendChild(newText4);
            } else {
                var newCell5  = newRow.insertCell(3);
                var newText5  = document.createTextNode("Pending"); 
                newCell5.appendChild(newText5);
            }  
        }
    }
    };
    xmlhttp22.open("GET","getRequestToShow.php/?id="+str,true);
    xmlhttp22.send();
}

这是 HTML 表格的 HTML。

<table id="customers">
<thead>
<tr>
<th>Username</th>
<th>Amount</th>
<th>Date</th>
<th>State</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

提前致谢!

标签: javascriptphpxmlmysqli

解决方案


将数据收集到一个数组中,然后做一个回显

$res = [];
while($row = mysqli_fetch_array($result)) {
    $res[] = [ 'first'=>$row['name'], 
                'second'=>$row['amount'],
                'third'=>$row['date'],
                'fourth'=>$row['state']
            ];
}

echo json_encode($res);

现在你将不得不改变你的 JS 总是期望一个数组或行,所以循环h2var


推荐阅读