在文档正文中,我们将其称为“ 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
我们如何获取行的内容并自动填写表格,它在哪里?
答案 0 :(得分:0)
整个javascript AJAX应该在HTML div #txtHint之后。
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
您也可以只返回行而不返回整个表。在主页上,将表创建为id'txtHint',并在响应中插入该行。