![](/img/trans.png)
[英]How do I detect in jQuery (AJAX) when a drop down item is selected on my HTML/PHP page?
[英]How do I use the selected item in a drop down list to pupulate on items in php?
我從數據庫中的表中填充下拉列表。 我試圖抓住用戶選擇的下拉列表中的選定項目,以便我可以查詢數據庫以獲取與該項目相關的更多信息。
<html>
<head></head>
<body>
<br>
<table id ="topnav" width="1100" border="0" align="center">
<tr>
<td colspan="2" style="background-color:#FFA500;">
<h1><table border="0">
<tr>
<th colspan="6"><img src ="../_images/Eu_flags.jpg" border="0" align="top" width="1100" height="180" />
</th>
</tr>
<table></h1>
</td>
</tr>
<tr valign="top">
<td style="background-color:#FFD700;width:150px;text-align:top;">
<b>Menu</b><br />
Select the state<br>
See rank of Universities<br />
Other information
</td>
<td style="background-color:#eeeeee;height:100px;width:940px;text-align:top;">
<?php
$con = mysql_connect("localhost","root","pasword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$result = mysql_query("SELECT lnamestate FROM state" );
while($row = mysql_fetch_array($result))
{
$lnamestate_id = $lnamestate['id'];
$row_lnamestate=$row['lnamestate'];
$row_block .= '<OPTION value="'.lnamestate_id.'">'.$row_lnamestate.'</OPTION>';
}
mysql_close($con);
?>
<label for="row">Select state</label>
<select name="lnamestateID"><?php echo $row_block; ?></select>
</td>
</tr>
<tr>
<td colspan="2" style="background-color:#FFA500;text-align:center;">
</td>
</tr>
</table>
</table>
</body>
</html>
首先,你需要給Select Control添加一個Event Handler,這樣當有東西被選中的時候,你就可以捕捉到這個事件,可以通過下面的實現;
<select name="ab" onchange="if (this.selectedIndex) doSomething();">
現在,持有索引可以知道已經選擇了什么,或者如果你想,通過索引,獲取選擇的項目並將其放入全局變量 javascript 中。
如果您在選擇項目時加載更多信息,請使用 ajax 和 xmlHttpRequest。在許多 web 應用程序中,當您使用 JQuery 時,它可以為您完成許多任務。 看看這里的 JQuery,它簡單易用,讓很多事情變得輕松。
您將需要 AJAX:
$('select.whatever').change(function(){
$.ajax({
url: '/path/to/your/script.php',
data: 'var='+$(this).val(),
type: 'POST',
success: function(data) {
$('.insert_element').html(data);
}
});
});
這會獲取正在更改的元素的值,將其發送到腳本(然后可以查詢數據庫),並返回特定元素中的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.