我想制作一个级联下拉列表,如果我选择一个类别子类别也将被更改。我在这里使用了Ajax。当我从下拉列表中选择类别列表时,我不知道为什么我的子类别无法在视图中加载。
这是我的路线:
<?php
Route::get('/', function () {
$categories=\App\Category::all();
return view('index')->with ('categories',$categories);
});
Route::get('/ajax-subcat',function(){
$cat_id = Input::get('cat_id');
$subcategories=Subcategory::where('category_id','=',$cat_id)->get();
return Response::json($subcategories);
});
这是我的查看页面:
<html>
<head>
<title>Cascading Dropwon</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3>Categories and Subcategories Ajax</h3>
<div class="col-lg-4">
{!! Form::open(array('url' => '','files'=>true)) !!}
{!! Form::token(); !!}
<div class="form-group">
<label for="">Categories</label>
<select class="form-control input-sm" name="category" id="category">
@foreach($categories as $category){
<option value="{{$category->id}}">{{$category->name}}</option>
}
@endforeach
</select>
</div>
<div class="form-group">
<label for="">Sub Categories</label>
<select class="form-control input-sm" name="subcategory" id="subcategory">
<option value=""></option>
</select>
</div>
{!!Form::close()!!}
</div>
</div>
<script>
$('#category').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
$.get('/ajax-subcat?cat_id='+ cat_id,function(data){
$('#subcategory').empty();
$.each(data,function(index,subcatObj){
$('#subcategory').append('<option value="'+subcatObj.id+'">'+
subcatObj.name+'</option>');
});
});
});
</script>
</body>
</html>
这是我的子类别模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model{
protected $table="subcategories";
protected $fillable = ['name','category_id'];
}