【发布时间】:2019-04-09 16:13:27
【问题描述】:
我有两个基于另一个类和部分的下拉字段。 我想要
Select * from sections where class_id=selected Class Id.
我使用 java 脚本 来管理它,但它不适合我。
我的下拉字段
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-6">
<label>Category</label>
<select class="form-control" name = "class">
<option value="0">Please Select Category</option>
@foreach($classses as $classs)
<option value="{{$classs->id}}">{{$classs->title}}</option>
@endforeach
</select>
</div>
</div>
<div>
<div class="col-md-6">
<label>Products</label>
<select class="form-control" name = "section">
<option value="0">Please Select Product</option>
@foreach($sections as $section)
<option value="{{$section->id}}">{{$section->title}}</option>
@endforeach
</select>
</div>
</div>
</div>
</div>
JavaScript
<script>
jQuery(document).ready(function ($) {
$('select[name=classs]').on('change', function () {
var selected = $(this).find(":selected").attr('value');
$.ajax({
url: base_url + '/classs/'+selected+'/sections/',
type: 'GET',
dataType: 'json',
}).done(function (data) {
var select = $('select[name=section]');
select.empty();
select.append('<option value="0" >Please Select Product</option>');
$.each(data,function(key, value) {
select.append('<option value=' + key.id + '>' + value.title + '</option>');
});
console.log("success");
})
});
});
路线
Route::get('/dropdown','DropDownController@index');
Route::get('classs/{id}/sections', 'DropDownController@getSection');
下拉控制器
public function index(){
$classses = Classs::all();
$sections =Section::all();
return view('classs.a', compact('classses','sections'));
}
public function getSection($id){
if($id!=0){
$sections = Classs::find($id)->sections()->select('id', 'title')->get()->toArray();
}else{
$sections = Section::all()->toArray();
}
return response()->json($sections);
}
}
类模式
class Classs extends Model
{
//
protected $fillable = [
'id',
'title',
];
public function section()
{
return $this->hasMany('App\Section');
}
}
部分模态
class Section extends Model
{
//
protected $fillable = [
'id',
'title',
'class_id', //foreign key of Classs
'user_id',
];
public function classs()
{
return $this->belongsTo('App\Classs');
}
但实际上,当我得到结果时,它会得到所有类和所有部分。 这可能是语法上的一些错误。我被困住了。在这种情况下请帮助我。
【问题讨论】:
-
您的输入名为
class,但在JS 中您正在寻找name=classs。 -
你是在说
-
没错。您可以在
change监听器中添加console.log以查看它是否被调用。 -
我改变了它,但它对我不起作用..
-
你能详细说明一下我在哪里可以添加console.log
标签: javascript php jquery ajax laravel