我有select标签和一系列选项选择属性,其值和内部文本存储在数据库中。
这是我在视图上显示数据的方式,通过为每个select标记调用foreach,总共2个:
{!! Form::label('category_id', 'Category:') !!}
<select class="form-control category_id" name="category_id">
@foreach($categories as $category)
<option value='{{ $category->id }}'> {{ $category->name }}</option>
@endforeach
</select>
{!! Form::label('subcategory_id', 'Subcategory:') !!}
<select class="form-control" name="subcategory_id" label="Subcategory">
@foreach($subcategories as $subcategory)
<option value='{{ $subcategory->id }}'> {{ $subcategory->name }}</option>
@endforeach
</select>
问题在于,我坚持以下想法:类别和子类别属于一对多关系,这意味着当用户单击某个类别时,应仅使用链接的值填充选择子类别选择的类别。
如何找到解决此问题的方法,我正在考虑创建一个ajax请求,但我无法确定如何填充选项选择属性。或者创建一个JSON(前端的所有工作)变量来存储子类别,并根据用户选择的类别更新select标签。
非常感谢任何帮助。
SOLUTION:
VIEW:
{!! Form::label('category_id', 'Category:') !!}
<select class="form-control" id="categories" name="category_id">
@foreach($categories as $category)
<option value='{{ $category->id }}'> {{ $category->name }}</option>
@endforeach
</select>
<div id="displayCategories" style="display:none">
{!! Form::label('subcategory_id', 'Subcategory:') !!}
<select class="form-control" id="subcategories" name="subcategory_id" label="Subcategory">
@foreach($subcategories as $subcategory)
<option value='{{ $subcategory->id }}'> {{ $subcategory->name }}</option>
@endforeach
</select>
</div>
JS&amp; JQUERY&amp; AJAX:
<script
src="https://code.jquery.com/jquery-3.1.1.js"
integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
crossorigin="anonymous"></script>
<script>
$('#categories').on('change',function(e) {
var cat_id = e.target.value;
//ajax
$.ajax({
url: '../ajax-subcat/{cat_id}', //note:that the path can be different for different purpose used, in a simple page -> '/ajax-subcat/{cat_id}' so use the console of your browser
type: 'GET',
data: {cat_id : cat_id},
success: function(response)
{
$('#subcategories').empty();
$('#displayCategories').show();
$.each(response, function(index, subcatObj) {
$('#subcategories').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
console.log(subcatObj);
});
}
});
});
</script>
ROUTE:
Route::get('ajax-subcat/{cat_id}', 'PostController@getAjax');
控制器:
public function getAjax()
{
$cat_id = Input::get('cat_id');
$subcategories = Subcategory::where('category_id', '=', $cat_id)->get();
return Response::json($subcategories);
}
不要忘记在控制器中引入相应的模型,输入和响应的外观。 就我而言:
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Category;
use App\Subcategory;
答案 0 :(得分:2)
您没有提到您使用的Laravel版本,因此实现可能略有不同。你可以通过ajax方法完成。您可以查看前端调用的Axios,但是当用户进行新选择时,您需要在select元素上设置事件侦听器。