laravel ajax 实现省市区三级联动
首先将省市区的数据存储到数据库中
sql文件地址:http://m.caomeipi.com/
html
<select name="province" style="width: 150px;" class="province form-control"> <option>==请选择省==</option> @foreach($province as $item) <option value="{{ $item->id }}">{{ $item->name }}</option> @endforeach </select> <select name="city" style="width: 150px;" class="city"> <option value="0">==市==</option> </select> <select name="area" style="width: 150px;" class="area"> <option value="0">==区/县==</option> </select>
js
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> <script type="application/javascript"> $(function () { //当省选项值发生变化的时候,发送ajax请求,获取对应的市区信息,并渲染 $('.province').change(function () { var province = $(this).val(); $.ajax({ //请求方式 type : "get", //请求的媒体类型 contentType: "application/json;charset=UTF-8", //请求地址 url : "getcity", //数据,json字符串 data : { "province":province }, //请求成功 dataType:"json", success : function(result) { //console.log(result) if(result.status == 0) { var citys = result.data; var optionstr = ""; //渲染city选择框 for(var i = 0; i < citys.length; i++) { var city = citys[i]; optionstr += "<option value='" + city.id + "'>" + city.name + "</option>"; } $('.city').html(optionstr); } else { alert(result.message); } }, //请求失败,包含具体的错误信息 error : function(e){ console.log(e.status); console.log(e.responseText); } }); }) }) $(function () { //当市选项值发生变化的时候,发送ajax请求,获取对应的区信息,并渲染 $('.city').change(function () { var city = $(this).val(); console.log(city); $.ajax({ //请求方式 type : "get", //请求的媒体类型 contentType: "application/json;charset=UTF-8", //请求地址 url : "getarea", //数据,json字符串 data : {"city":city}, //请求成功 dataType:"json", success : function(result) { //console.log(result) if(result.status == 0) { var areas = result.data; console.log(areas); var optionstr = ""; //渲染city选择框 for(var i = 0; i < areas.length; i++) { var area = areas[i]; optionstr += "<option value='" + area.id + "'>" + area.name + "</option>"; } $('.area').html(optionstr); } else { alert(result.message); } }, //请求失败,包含具体的错误信息 error : function(e){ console.log(e.status); console.log(e.responseText); } }); }) }) </script>
controller
//添加页面 并获取省的信息 public function addpaper(){ $province = DB::table('region')->where('pid',100000)->get(); return view('addpaper',compact('province')); } //市三级联动 public function getCity(Request $request) { $province = $request['province']; $citys = DB::table('region')->where('pid','=',$province)->get()->toArray(); return json_encode(['status' => 0, 'data' => $citys]); } //区三级联动 public function getArea(Request $request) { $city = $request['city']; $area = DB::table('region')->where('pid','=',$city)->get()->toArray(); return json_encode(['status' => 0, 'data' => $area]); }