javascript - 无法从 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>
提前致谢!
解决方案
将数据收集到一个数组中,然后做一个回显
$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 总是期望一个数组或行,所以循环h2
var
推荐阅读
- node.js - router.get 和 app.get 有什么区别?
- javascript - 如何使用 node.js 从 API 调用中打开数据并将数据写入文件
- mule - 在 Dataweave 2.0 中用空白替换 Null
- jquery - TS2702:“JQuery”仅指一种类型,但在此处用作命名空间
- c# - Azure Function App 无法加载 IOptionsFormatter
- android - 是否可以仅使用 cmake 构建本机 android 应用程序(ndk)?
- java - 引导错误包含 org.eclipse.core.runtime 包,但不是 osgi.bundles 有问题
- python - 如何在没有 NoneType 没有属性“get”的情况下链接 .get()s?
- string - 将值从 get 传递到 url
- python - 使用 Python 比较两个 excel 文件