Leaflet项目中基于PHP返回数据调整AJAX逻辑填充国家下拉列表
问题原因
你的AJAX代码访问的JSON结构和PHP实际返回的结构不匹配:
- PHP代码已经把GeoJSON里的
properties字段直接提取出来存入output['data']数组,所以返回的result.data本身就是国家属性数组,没有你代码里写的country层级 - 不需要再次访问
.properties字段,PHP已经把这层内容直接提取到了数组元素中
调整后的完整AJAX代码
// 先清空下拉框,避免重复追加选项 $('#select-country').empty(); $.ajax({ url:"js/geoJson.php", type: 'POST', dataType: "json", success: function(result) { // 直接遍历result.data即可 for (var i=0; i<result.data.length; i++) { $('#select-country').append($('<option>', { value: result.data[i].iso_a2, text: result.data[i].name, })); } }, // 新增错误回调,方便后续排查请求问题 error: function(xhr, err) { console.log('请求失败:', err); } });
可选简化写法
用forEach循环让代码更简洁:
success: function(result) { result.data.forEach(countryItem => { $('#select-country').append(new Option(countryItem.name, countryItem.iso_a2)); }) }
内容的提问来源于stack exchange,提问作者CannDo
相关产品推荐
相关产品推荐

