1、表的樣式
區的pid是市的id
2、定義路由
//獲取省市區 Route::get('','Controller@mentod')->name('');
3、HTML代碼(市的數據是第一次加載時得到的數據)
<div class="row cl"> <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>小區地址:</label> <div class="formControls col-xs-4 col-sm-4"> <select name="fang_province" style="width: 100px;" onchange="selectCity(this,'fang_city')"> <option value="0">==請選擇省==</option> @foreach($cityData as $item) <option value="{{ $item->id }}">{{ $item->name }}</option> @endforeach </select> <select name="fang_city" id="fang_city" style="width: 100px;" onchange="selectCity(this,'fang_region')"> <option value="0">==市==</option> </select> <select name="fang_region" id="fang_region" style="width: 100px;"> <option value="0">==區/縣==</option> </select> </div> <div class="formControls col-xs-4 col-sm-5"> <input type="text" class="input-text" name="fang_addr" placeholder="小區詳情地址和房源說明"> </div> </div>
4、js代碼
// 下拉選擇市和地區 // obj 當前對象 // selectName 給選中下個處理html的ID 字符串 function selectCity(obj, selectName) { // 得到選中的值 let value = $(obj).val(); // 以省份ID得到市 發起ajax請求 $.get('{{ route('admin.fang.city') }}', {id: value}).then(jsonArr => { let html = '<option value="0">==市==</option>'; // 循環 map for for in for of $.each jsonArr.map(item => { var {id, name} = item; html += `<option value="${id}">${name}</option>`; }); $('#' + selectName).html(html); }); }
5、服務器端代碼
// 獲取城市 public function city(Request $request) { $data = City::where('pid', $request->get('id'))->get(['id', 'name']); return $data; }