我尝试搜索并尝试不同的东西,但遗憾的是我无法找到适合我情况的答案。
由于我的(ajax)查询
,我有这种json格式[{"id":1,"region":"Region I","state_id":1},{"id":2,"region":"Region II","state_id":1},{"id":3,"region":"Region III","state_id":1},{"id":4,"region":"Region IV-A","state_id":1},{"id":5,"region":"Region IV-B","state_id":1},{"id":6,"region":"Region V","state_id":1},{"id":16,"region":"CAR","state_id":1},{"id":17,"region":"NCR","state_id":1}]
如何在我的区域下拉列表中填充此数据?我试过这个
<script type="text/javascript">
$("#state").on('change', function () {
var state = $('#state').val();
$.ajax({
type :"GET",
url :"http://localhost/laravel/public/getregions",
dataType:"html",
data :{ stateid:state },
success :function(response){
alert(response);
$($.parseJSON(response)).map(function () {
return $('<option>').val(this.id).text(this.region);
}).appendTo('#region');
}
});
});
</script>
但我得到一个TypeError:a是未定义的错误。我不知道我的格式是否有什么问题,或者我是如何解析json的。
答案 0 :(得分:0)
map函数需要一个数组作为第一个参数,一个函数作为第二个参数。
你得到一个对象数组作为答案,所以首先将它作为参数提供给map函数。然后在回调中你可以得到每个对象:
$.map(response,function(element,index){ ... });
检查jsfiddle,看看它是否适合你。
答案 1 :(得分:0)
要从ajax调用填充您的区域下拉列表,我会尝试这种方法:
$.getJSON(url, function(response) {
var regions = [];
$.each(response, function(i, region) {
regions.push('<option value="' + region.id + '">' + region.region + '</option>');
$("#region").html(regions.join(''));
});
});
虽然没有经过充分测试,但类似的东西应该可行。祝你好运:)