laravel - 级联下拉菜单在 Laravel 7 中不起作用
问题描述
我正在尝试在 mvc 中使用级联下拉列表。主要类别正在工作,但在子类别中有一些问题。当我从主要类别中选择时,它没有显示任何价值
在刀片中:
<div class="form-group">
<label for="cat_id">Category <span class="text-danger">*</span></label>
<select name="cat_id" id="cat_id" class="form-control">
<option value="">--Select any category--</option>
@foreach($categories as $key=>$cat_data)
<option value='{{$cat_data->id}}'>{{$cat_data->title}}</option>
@endforeach
</select>
</div>
<div class="form-group" id="child_cat_div">
<label for="child_cat_id">Sub Category</label>
<select name="child_cat_id" id="child_cat_id" class="form-control">
<option value="">--Select any category--</option>
</select>
</div>
@push('scripts')
<script>
$('#cat_id').on('change',function(e) {
var cat_id=$(this).val();
// alert(cat_id);
if(cat_id !=null){
// Ajax call
$.Ajax({
url:"/backend/category/"+cat_id,
data:{
_token:"{{csrf_token()}}",
id:cat_id
},
type:"POST",
success:function(response){
if(typeof(response) !='object'){
response=$.parseJSON(response)
}
// console.log(response);
var html_option="<option value=''>Select sub category</option>"
if(response.status){
var data=response.data;
// alert(data);
if(response.data){
$('#loader').css("visibility", "visible");
// $('#child_cat_div').removeClass('d-none');
$.each(data,function(id,title){
html_option +="<option value='"+ id +"'>" + title +"</option>"
});
}
else{
}
}
else{
$('#child_cat_div').addClass('d-none');
}
$('#child_cat_id').html(html_option);
}
});
}
else{
}
}) </script> @endpush
在路线:
Route::POST('/category/{id}','Admin\CategoryController@getChildByParent');
在文章控制器中:
public function create()
{
$categories=Category::where('is_parent',1)->get();
$photos = Photo::all();
$tags = Tag::all();
$articles = Article::all();
return view('backend.articles.create',
compact('categories','photos','tags','articles'));
}
在类别控制器中:
public function getChildByParent(Request $request){
$category=Category::findOrFail($request->id);
$child_cat=Category::getChildByParentID($request->id);
return response()->json([$child_cat]);
return response()->json([
'child_cat' => $child_cat]);
}
在模型类别中:
public static function getChildByParentID($id){
return Category::where('parent_id',$id)->orderBy('id','ASC')->pluck('title','id');
}
解决方案
推荐阅读
- android-studio - Android Studio 的 Memory Profiler 中的“总计数”指标是什么?
- python - 从右列中删除 NaN 值,同时在左列中保留值
- grails - Grails 使用自动 id 在域持久性中创建附加属性
- php - PHP/Laravel 获取类名中的最后一个单词:App\Models\Example\Class;并将其小写:class
- r - 使用自动填充扩展编辑数据表?
- dart - 如何在flutter中访问Path对象存储的绘图命令?
- kubernetes - 使用 Helm 在 DigitialOcean Kubernetes 集群上安装 Traefik 无法为 LoadBalancer 创建外部 IP 地址
- javascript - JSON 字符串在值周围有方括号
- c++ - 了解 do/while 循环 C++
- java - ClassCastException:org.apache.activemq.ra.ActiveMQConnectionFactory 不能转换为 javax.jms.ConnectionFactory