我是ajax的初学者。现在我正在使用Laravel 5.4,我想填充我在控制器中查询的城市,以便在我的视图中输出。
这是我的代码:
function getCities(province_id) {
$('#city_id').empty();
$.ajax({
url: "{{ url('city') }}/" +province_id,
type: "GET",
dataType: "JSON",
success: function(data) {
var opts = $.parseJSON(data);
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
$('#city_id').append('<option value="' + d.city_id + '">' + d.city_name + '</option>');
});
}
});
}
在我的控制器中,我有这个:
public function getmycity($province_id) {
$cities = DB::table('cities')
->select('cities.city_id','cities.city_name')
->where(['cities.province_id' => $province_id])
->get();
return $cities;
}
我已经在网络中返回了json对象,并且我已经看到了所有数据对象。
JSON
0 Object
city_id 28
city_name Test City
请帮我把它全部放在我的选择中。
我没有收到任何错误,但它没有使用我的查询值填充我的选择类型。
这是我的观点:
<div class="form-group">
<label class="control-label col-sm-4" for="email">City/Municipality :</label>
<div class="col-sm-8">
<select class="form-control" id="city_id" name="city_id">
<option>Select city/municipality</option>
</select>
</div>
</div>
答案 0 :(得分:0)
尝试在纯数组中更改db结果,如下所示:
$cities = json_decode(json_encode($cities),true);
然后return
:
return $cities;
和,
当您编写dataType:'JSON'时,无需解析您的回复,您可以尝试不var opts = $.parseJSON(data);
这样var opts = data;
希望这会对你有帮助......