【发布时间】:2010-09-07 08:45:09
【问题描述】:
我有一个表单,其中包含一个名为 Client_ID 的选择以及一些其他文本输入。我需要的是,当用户选择 Client_ID 时,我的字段 Address1、Address 2 等应该按照数据库查询的结果填充
SELECT Address1, Address2 from Client where Client_ID = Client_ID
我知道这有点像菜鸟问题,但非常感谢您提供最简单和最好的方法。
【问题讨论】:
我有一个表单,其中包含一个名为 Client_ID 的选择以及一些其他文本输入。我需要的是,当用户选择 Client_ID 时,我的字段 Address1、Address 2 等应该按照数据库查询的结果填充
SELECT Address1, Address2 from Client where Client_ID = Client_ID
我知道这有点像菜鸟问题,但非常感谢您提供最简单和最好的方法。
【问题讨论】:
首先从here 下载 jquery 并将其包含在您的应用程序中。
如果home.php,你下载的jquery文件(jquery-1.4.2.min.js)和getData.php在同一个文件夹,那么您的 home.php 将如下所示:
home.php(包含您的表单的文件)
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#Client_ID').live('change', function(event) {
$.ajax({
url : 'getData.php',
type : 'POST',
dataType: 'json',
data : $('#myform').serialize(),
success: function( data ) {
for(var id in data) {
$(id).val( data[id] );
}
}
});
});
});
</script>
</head>
<body>
<form id='myform'>
<select name='Client_ID' id='Client_ID'>
<option value=''>Select</option>
<option value='1'>Client 1</option>
<option value='2'>Client 2</option>
</select>
<input type='text' name='address1' id='address1'>
<input type='text' name='address2' id='address2'>
<select name='gender' id='gender'>
<option value=''>Select</option>
<option value='1'>Male</option>
<option value='2'>Female</option>
</select>
</form>
</body>
</html>
getData.php
<?php
$clientId = $_POST['Client_ID']; // Selected Client Id
$query = "SELECT Address1, Address2 from Client where Client_ID = $clientId";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC)
$add1 = $row[Address1];
$add2 = $row[Address2];
$gender = 1;
$arr = array( 'input#address1' => $add1, 'input#address2' => $add2, 'select#gender' => $gender );
echo json_encode( $arr );
?>
我已经在我的机器上测试了这段代码,它正在工作。
【讨论】:
<script></script> 标记中关闭它并使用准备好的功能。查看已编辑的答案。现在在 head 部分添加了 jquery 代码。仔细阅读整个答案,然后再试一次。如果不成功,请再次在这里报告,我会尽力提供帮助。
阅读this tutorial。我认为它可能会帮助您理解将数据从客户端移动到服务器的概念,反之亦然。
请记住,在您的情况下,您需要组合事件。
$(document).ready(function(){
$("#my_select_box").change(function()
{
//send the data to the server as in the tutorial above
});
});
【讨论】: