0

我从 MYSQL 数据库中提取数据以填充下拉

<td class="<?php print $Bank_ca_error;?>">Bank Name</td> <td> <select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> <option><?php print $_SESSION['Bank_ca'] ;?></option> <?php //Get Data to populate drop down $BankQuery = "SELECT BankName FROM tblbank ORDER BY BankName"; $BankResult = mysql_query ($BankQuery); While($nt=mysql_fetch_array($BankResult)) { print"<option $nt[BankName]>$nt[BankName]</option>"; } ?> </select> </td> 

我想根据选择的值填充文本输入。所以基本上从列表中选择银行并让它在文本输入中自动填充通用分行代码。

我看到了一个使用 Jquery 的示例,但在这方面我完全是个菜鸟,我无法让它正常工作

我在 Head 部分添加了以下内容

<script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#Bank').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> 

然后我将此添加到 getData.php 文件中

<?php include "../../../includes/dbinfo.inc"; //Connect to database     mysql_connect($db_host, $db_username, $db_password); @mysql_select_db($db_database) or     die("Unable to select database"); $BankName = $_POST['Bank']; // Selected Bank $query = "SELECT * FROM tblbank WHERE BankName ='{$BankName}'"; $result = mysql_query($query); $row = mysql_fetch_array($result) $BranchCode = $row['UniversalCode']; $arr = array(     'input#BranchCode' => $BranchCode ); echo json_encode( $arr ); ?> 

并将以下内容添加到相关的输入和下拉列表中

<form id='myform'> </form>

我尝试在此站点的其他地方使用解决方案,但无法使其正常工作

非常感谢您的帮助

4

1 回答 1

0

如果我正确理解你想要做什么,那么你不需要ajax,试试这样的

<?php
include "../../../includes/dbinfo.inc"; 
//Connect to database
mysql_connect($db_host, $db_username, $db_password); @mysql_select_db($db_database) or die("Unable to select database");

$res = mysql_query("SELECT UniversalCode, BankName FROM tblbank ORDER BY BankName");
while($row = mysql_fetch_assoc($res)) {
    // associative array of banks
    $banks[$row['UniversalCode']] = $row['BankName'];
}
?>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
    $('#Bank').change( function() {
        // enter in an empty field code of the selected bank
        $('#UniversalCode').val( $(this).val() );
    });
});
</script>
<td class="<?php print $Bank_ca_error;?>">Bank Name</td> 
<td> 
<select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> 
    <? foreach($banks as $code=>$name) { ?>
        <option value="<?=$code?>"><?=$name?></option> 
    <? } ?>
</select>
<input value="" id="UniversalCode">
</td> 
于 2012-05-21T14:47:22.493 回答