我尝试获取我选择的 state(province)
的 city
列表,城市名称返回为 undefined
这是我的 Controller 方法
public function index(Request $request) {
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxx');
$province = $rajaongkir->province();
$origin = 152; //Jakarta
$destination = 178; // Kediri
$weight = 1;
$courier = 'tiki'; // jne, tiki, pos
$cost = $rajaongkir->cost($origin, $destination, $weight, $courier);
return view('front.raja', compact('province', 'cost'));
}
public function getCityList($province)
{
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxx');
$city = $rajaongkir->city($province);
return response()->json($city);
}
我的 Blade 代码:
<form action="">
{{csrf_field()}}
<select name="province" id="">
<option class="form-control" value="">Select Province</option>
@foreach ($province->data as $info)
<option value="{{$info->province_id}}">{{$info->province}}</option>
@endforeach
</select>
<select name="city" id="">
<option class="form-control" value="">Select City</option>
</select>
<div style="margin-top: 30px;">
Destination:
{{$cost->meta['destination']->province}},
{{$cost->meta['destination']->type}},
{{$cost->meta['destination']->city_name}},
{{$cost->meta['destination']->postal_code}}.
@foreach($cost->data as $option)
<h3>{{$option->code}} <small>{{$option->name}}</small></h3>
@foreach($option->costs as $cost)
@foreach($cost->cost as $c)
<label class="radio">
<input name="post" value="{{ $c->value }}" type="radio">{{$cost->service}} / {{ $c->value }} Rp - {{ $c->etd }} hari @if(!empty($c->note))- {{ $c->note }} @endif
</label>
@endforeach
@endforeach
@endforeach
</div>
<button type="submit" class="btn btn-default">save</button>
</form>
我的 javascript 代码:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="province"]').on('change', function() {
var provinceID = $(this).val();
if(provinceID) {
$.ajax({
url: '{{ url('get-city-list') }}/'+encodeURI(provinceID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option class="form-control" value="'+ value['city_id'] +'">'+ value['city_name'] + ' - ' + value['type'] +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
</script>
这是我的代码的结果:
If I add
alert(JSON.stringify(value, null, 4));
beforeappend
will return:
这是我在Logic
中试图实现的:
- 选择省份
- 获取该省的城市列表
- 获取该城市的 ID 并将其添加为我的
$destination
到 Index 函数$destination = 178;//凯迪里
The point is all this has happen with ajax, why? because I try to use this form in my cart before checkout so when I hit checkout button is already included shipping price.
最佳答案
查看您的评论,您似乎正在尝试迭代错误的对象:
使用:
$.each(data.data
不仅仅是:
$.each(data
这是因为来自 ajax 成功的 data
返回为:
{
code:200,
data:[
...etc.
],
error: ...etc.
}
关于javascript - 根据 Laravel 中未定义的父 ID 获取 ajax 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434099/