我的数据库中有两个字段 滚动否和名称 我设计了一个html表单,其中有两种输入类型 一个 - > “滚不” 和其他是“名字”
我希望当我在卷号字段中输入卷号并按Tab键时,名称字段应该从数据库中自动填充。
我的代码在这里
的index.php
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var searchTimeout; //Timer to wait a little before fetching the data
$("#roll").keyup(function() {
searchKey = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(searchKey);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers (searchKey) {
$.ajax({
url: 'getUser.php',
type: 'POST',
dataType: 'json',
data: {value: searchKey},
success: function(data) {
if(data.status) {
$("#name").val(data.userData.name);
} else {
// Some code to run when nothing is found
}
}
});
}
</script>
</head>
<table>
<tr>
<td>Roll</td>
<td><input type="text" name="roll" id="roll" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
</table>
</html>
getUser.php
<?php
include "db.php";
$response = Array();
$response['status'] = false;
$query = mysql_query("SELECT `name` FROM `tab` WHERE `roll` LIKE '%".$_POST['value']."%' LIMIT 1"); //Or you can use = instead of LIKE if you need a more strickt search
if(mysql_num_rows($query)) {
$userData = mysql_fetch_assoc($query);
$response['userData'] = $userData;
$response['status'] = true;
}
echo json_encode($response);
?>
答案 0 :(得分:0)
您可以使用ajax
执行此操作。Ajax
实时与PHP
进行通信,因此无需按提交按钮即可自动填写名称字段。
XMLHttpRequest()
是执行此任务所需的功能。请对XMLHttpRequest()
进行一些研究,这将有助于您更好地了解。
function auto(roll){
var roll=roll;
var ajax=new XMLHttpRequest();
ajax.open("post","yourfile.php",true);
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
ajax.onreadystatechange=function(){
if(ajax.readyState == 4 && ajax.status == 200){
document.getElementById(Name).value=ajax.responseText; //This line will fill the Name field automatically
}
}
ajax.send("roll_num="+roll);
}
因此,在这种情况下,在您的php文件yourfile.php
中,为name
获取roll
。 echo
{php}文件中name
,name
值将传递给ajax asynchronously
。然后name
字段将自动填充
这是您获得预期结果的方式。