我正在尝试在laravel和ajax中创建一个依赖的下拉菜单。我有两张桌子,分区和比萨。地区可以有很多比。当我选择一个区时,我正试图做点什么,只有那个区下面的人才会显示。
$data=Thana::select('name','id')->where('district_id',$request->id)->take(100)->get();
return response()->json($data);//
这应该返回与所请求的区域ID匹配的名称和id,但由于某种原因这是失败的。正在显示正确的district_id。
这是我的控制器代码。
use Illuminate\Http\Request;
use App\District;
use App\Thana;
use App\Atm;
class AtmController extends Controller
{
public function atmfunct(){
$atmdistrict=District::all();
$atmthana=Thana::all();//get data from table
return view('MasterForms.atmlist',compact('atmthana','atmdistrict'));//sent data to view
}
public function findThanaName(Request $request){
//if our chosen id and products table prod_cat_id col match the get first 100 data
//$request->id here is the id of our chosen option id
$data=Thana::select('name','id')->where('district_id',$request->id)->take(100)->get();
return response()->json($data);//then sent this data to ajax success
}
}
这是我连接jquery请求的部分。
<span>District: </span>
<select style="width: 200px" class="districtt" id="district_id">
<option value="0" disabled="true" selected="true">-Select-</option>
@foreach($atmdistrict as $cat)
<option value="{{$cat->id}}">{{$cat->name}}</option>
@endforeach
</select>
<span>Thana Name: </span>
<select style="width: 200px" class="name">
<option value="0" disabled="true" selected="true">Thana Name</option>
@foreach($atmthana as $cat)
<option value="{{$cat->id}}">{{$cat->name}}</option>
@endforeach
</select>
</center>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.districtt',function(){
console.log("hmm its change");
var district_id=$(this).val();
console.log(district_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findThanaName')!!}',
data:{'id':district_id},
success:function(data){
console.log('success');
//console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose division</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id+'">'+data[i].name+'</option>';
}
div.find('.name').html(" ");
div.find('.name').append(op);
},
error:function(){
console.log('error');
}
});
});
});
</script>
我无法弄清楚我哪里出错了。
答案 0 :(得分:0)
您认为代码的哪一部分失败了?请提供更多信息:
'{!!URL::to('findThanaName')!!}'
看起来像什么?'{!!URL::to('findThanaName')!!}'
district_id
时的原始JSON示例
'{!!URL::to('findThanaName')!!}'
。我会根据您稍后提供的信息编辑我的答案。我还没有足够的声誉发表评论:p