编辑页AJAX联动国家城市下拉框初始加载无值问题排查
问题原因排查
- 核心问题是你的国家下拉框没有设置
id="country"属性:你在$(document).ready里用$('#country').val()拿值,但HTML中<select>只有name="country"没有对应id,jQuery选择器找不到目标元素,返回值自然是undefined,导致初始AJAX请求参数异常,无法返回带选中状态的城市选项。 - 次要优化点:初始请求没有做空值判断,参数无效时依然会发起无意义的AJAX请求。
解决方案
- 给国家下拉框添加id属性,修改edit.php里的国家下拉代码:
<!-- 新增id="country"属性 --> <select name="country" id="country" onchange="getcities($(this).val())" required> <option value="<?php echo set_value('country'); ?>">Select Country</option> <?php if($countries) foreach($countries as $country): ?> <option value="<?php echo $country['id']; ?>" <?php echo ($listing[0]['country'] == $country['id'])?'selected="selected"':''?>><?php echo $country['name']; ?></option> <?php endforeach; ?> </select>
- 给getcities函数添加空值拦截,避免无效请求:
function getcities(obj){ // 新增空值判断,参数异常时直接终止 if(!obj) return; console.log(obj); var dataString = new Object(); dataString.emirate = '<?php echo $property->emirate ?>'; $.ajax({ type: "get", dataType:"json", url: "<?php echo site_url('listings/ajaxgetcitiesedit'); ?>/"+obj, data: dataString, success: function(e) { $('#emiratewrap').html(e.result); $bb = "<?php echo $property->status; ?>"; if($bb=="Y") {$("#emiratewrap select").addClass("disabled"); } // 如果使用了select2插件,可加下面这行保证组件样式和选中状态正常渲染 // $('#emirate').select2(); } }); }
修改完成后页面初始加载就能正确拿到当前选中的国家ID,请求接口返回的城市下拉会自动带上数据库中存储城市的selected属性,默认选中对应选项。
内容的提问来源于stack exchange,提问作者H2O
相关产品推荐
相关产品推荐

