我在更新表格时遇到问题。以这种形式,我从数据库中获取结果并显示值。有取决于城市和地区的下拉菜单。我获取城市比较和选定值显示,但是以相同的方式,依赖下拉列表意味着不会填充本地下拉列表。参见代码。
<div class="col-md-3">
<label for="enq_city">City<span class="red">*</span></label>
<?php if (isset($cities) && !empty($cities)) { ?>
<select required="" class="form-control" id="enq_city" name="enq_city">
<option value="">Choose City</option>
<?php foreach ($cities as $city) {
if($city->city_id == $result[0]->enq_city) {
$selected = "selected";?>
<option <?php echo $selected ?> value="<?php echo $city->city_id; ?>">
<?php echo $city->city_name; ?></option>
<?php } ?>
<?php } ?>
</select>
<?php } ?>
</div>
<div class="col-md-3">
<label for="enq_locality">Locality<span class="red">*</span></label>
<select required="" class="form-control" id="enq_locality" name="enq_locality">
</select>
</div>
我的Ajax代码
<script type="text/javascript">
$(document).ready(function() {
$('select[name="enq_city"]').on('change', function() {
var cityId = $(this).val();
alert(cityId);
if(cityId) {
$.ajax({
url: 'getLocality/'+cityId,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="enq_locality"]').empty();
$.each(data, function(key, value) {
$('select[name="enq_locality"]').append('<option value="'+ value.locality_id +'">'+ value.locality_name +'</option>');
});
}
});
}else{
$('select[name="enq_locality"]').append('<option value="">No Locality Found</option>');
}
});
});
答案 0 :(得分:0)
根据我对您的问题的理解,似乎您正在以某种方式刷新此页面(用于“编辑”)并从数据库中提取数据,并希望使这些值从负载中出现。
如果是这种情况,那么您在加载页面时看不到任何内容的原因是因为您仅在select的“更改时”加载数据-并且在加载页面时,没有“更改” '-它刚刚加载,因此JS永远不会触发。
获取加载数据的一种简单方法是稍微修改JS .....
<script type="text/javascript">
$(document).ready(function() {
// pull the AJAX out to a function that can be used later
function call_ajax(cityId){
if(cityId){
$.ajax({
url: 'getLocality/'+cityId,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="enq_locality"]').empty();
$.each(data, function(key, value) {
$('select[name="enq_locality"]').append('<option value="'+ value.locality_id +'">'+ value.locality_name +'</option>');
});
}
});
}else{
$('select[name="enq_locality"]').append('<option value="">No Locality Found</option>');
}
}
$('select[name="enq_city"]').on('change', function() {
var cityId = $(this).val();
alert(cityId);
call_ajax(cityId);
});
// now, we make sure that 'enq_locality' is populated on loading the page
// NOTE: this presumes that $city->city_id exists
// from the example code it is also presumed so not checked here
call_ajax("<?php echo $city->city_id; ?>");
});
该代码未经测试(因为您没有提供完整的示例进行测试.....),尽管应该就至少一种获取页面加载数据的方式给出一些想法。
如果我不理解该问题,请提供更多代码和更多有关此情况的描述。