【问题标题】:使用 Javascript Laravel 8 动态选择
【发布时间】:2022-01-23 17:02:12
【问题描述】:

我正在使用 Laravel 8 开发一个项目,我需要在表单中创建一个动态下拉列表来创建类别。第一个下拉菜单必须显示商店,第二个下拉菜单应显示该商店的类别。我不知道我是否应该使用 javascript 或其他方式来执行此操作。

表格:

<label for="store_id">Store</label>
<select id="store_id" name="store_id" class="custom-select">                 
@foreach($stores as $store)
   <option value="{{ $store->id}}">{{ $store->name}}</option>
@endforeach
</select>

<label for="parent_category">Parent Category</label>
<select  id="parent_category" name="parent_category" class="custom-select">                                              
</select>

类别表

id store_id parent_category_id name

存储表

id name

CategoryController.php

public function create()
{              
  $stores = Store::all();
  $categories = Category::all();                    

  $data= [            
    'stores ' => $stores ,
    'categories ' => $categories 
  ];

return view('category.create')->with($data);
}

【问题讨论】:

    标签: javascript laravel dynamic html-select


    【解决方案1】:

    您可以使用 jQuery 实现这种方法:

    通过关系获取商店类别,具体取决于您的关系类型一对多、多对多等:

    public function Storecategories()
    {
        return $this->hasMany('App/Models/Categories','store_id');
    }
    

    在您的控制器功能中并获取商店类别:

    //return store categories with ajax response using relationship
    $store_categories = StoreModel::find($store_id)->Storecategories()
    //if any where clause you want to add
    ->where('Your conditions')
    ->get();
    
    return response()->json(['store_categories'=>$store_categories->toArray() ]);
    

    在选择商店时发送ajax请求,获取类别数组并动态创建类别html:

    //Perform action on selection of store
    $(document).on('change','#store_id',function(){
       $.ajax({
                type: "POST",
                url: Your ajax url,
                data[store_id:stroe_id , _token:token],
                success: function (data) {
                    let categories = data.store_categories;
                    let html = '';
                    $.each(categories ,function(i,v){
                        html += '<option value="'+v.id+'">'+v.name+'</option>';
                    });
                    $("#parent_category").html(html);
                }
            });
    }); 
    

    【讨论】:

    • “公共函数 Storecategories()”应该在 Store Model 中,对吧?而且我不明白应该在 Ajax Url 中写入哪个 url。
    • 是的关系应该在商店模型中
    • 谢谢,还有 Ajax Url 字段?我不知道在那儿写什么。
    • web.php 文件中创建一个路由,并在一个ajax url 中给它一个路径。
    • Route::post('Your_cutom_path', 'Your_Controller_Name@Controller_function_name');,将此路径提供给 ajax url。
    猜你喜欢
    • 2021-01-06
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2021-04-23
    • 2018-06-09
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多