【发布时间】:2018-10-21 17:43:22
【问题描述】:
在文档的正文中,我们称之为“form.php”,我们有以下内容:
在head 上,我们有一段 JavaScript 代码:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getchauffeur.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
我们查询数据库并填充下拉列表。我们使用 (showUser) 切换内容:
<div>
<?
$result = $mysqli -> query("select id, nomchauffeur from chauffeurs");
echo "<select name='id' onchange='showUser(this.value)'>";
while ($row = $result -> fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['nomchauffeur'];
echo '<option value="'.$id.
'">'.$name.
'</option>';
}
?>
在这里,我们仍然在身体中。我们把AJAX的内容放到div。
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
</div>
这是我们用 AJAX 请求的内容填充表单字段的脚本:
<script>
var table = document.getElementById('table');
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
//rIndex = this.rowIndex;
document.getElementById("nomchauffeur").value = this.cells[0].innerHTML;
document.getElementById("prenomchauffeur").value = this.cells[1].innerHTML;
document.getElementById("agechauffeur").value = this.cells[2].innerHTML;
document.getElementById("cinchauffeur").value = this.cells[3].innerHTML;
};
}
</script>
现在这里是我们的 getchauffeur.php:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','nouveau');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$sql="SELECT * FROM chauffeurs WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>nom</th>
<th>prenom</th>
<th>age</th>
<th>adresse</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['nomchauffeur'] . "</td>";
echo "<td>" . $row['prenomchauffeur'] . "</td>";
echo "<td>" . $row['agechauffeur'] . "</td>";
echo "<td>" . $row['adressechauffeur'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
问题:如果表格在同一页上,一切正常。但是这里的 AJAX 请求限制我们将表放在其他 php 页面(chauffeur.php)中。
我们需要的是通过单击下拉Change 操作中显示的行来自动填充表单字段。似乎插入到“chauffeur.php”内的表中的行没有打印在 html DOM 上。当我们点击页面查看源时,它只显示:
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
而不是以下字段的内容:
nomchauffeur prenomchauffeur agechauffeur adressechauffeur
我们如何获取行的内容并自动填写表格,它在哪里?
【问题讨论】:
-
检查您的网络,当下拉列表更改时,您对请求的响应是什么。
-
getchauffeur.php?q=1 getchauffeur.php?q=2 getchauffeur.php?q=3
-
nom prenom age adresse chaugffeur1 prenomc1 23 addresssec1 -
所以,你的回答是正确的。看看你是否在响应文本下得到它。
标签: javascript php html ajax