嗨,我正在做依赖下拉列表。
如果表{t}中没有<select>
,则代码可以正常工作。
但是如果select标签在表td中,则ajax将无法返回到表td中的元素。我怎么能解决这个问题?
<table>
<tr>
<td>
<label>Country:</label><br/>
<select name="country" id="country-list" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</td>
</tr>
</table>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
</script>
在get_state.php页面
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select State</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
}
}
?>
答案 0 :(得分:1)
您的代码显示正常。在不知道你的数据的情况下,不可能说出什么是错的。复制此代码段并尝试通过输入实际状态数据来重现您的问题。
/// fake jQuery.ajax
function $ajax(params) {
params.success('<option value="1">S1</option><option value="2">S2</option><option value="3">S3</option><option value="4">S4</option>');
}
function getState(val) {
$ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<label>Country:</label><br/>
<select name="country" id="country-list" onChange="getState(this.value);">
<option value="">Select Country</option>
<option value="1">Country 1</option>
</select>
</td>
</tr>
<tr>
<td>
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</td>
</tr>
</table>