【发布时间】:2014-12-07 19:47:35
【问题描述】:
我的数据库中有两个字段 卷号和名称 我设计了一个 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);
?>
【问题讨论】:
-
听起来像是 AJAX 的工作
-
但是如何?我该怎么做呢
-
广义地说,你需要做一些工作尝试一下,如果\当你遇到问题时用 code
标签: javascript php html database