Laravel 5.6:从下拉列表中获取选定值以在另一个下拉列表中使用它

Laravel 5.6: Get selected value from a dropdown to use it in another

6,我正在使用下拉列表从数据库中读取列 table。我只想获取该下拉列表中的选定值,并使用它创建一个新查询,该查询将填充到新的下拉列表中。

阅读并查看几个示例后,我看到有人使用 ajax 和其他人使用 laravel HTTP 请求,例如 $request->get() 所以我不知道该采取哪种方式,因为我'我对其中任何一个都不熟悉,即使尝试了几次也无法正常工作。

任何人都可以告诉我 best/efficient 的方法吗?是否可以仅使用 php 或我缺少的 laravel 中的某些功能来做到这一点?

这是我的控制器:

public function selectsector() //this is the dropdown #1 that works fine
{ 
 $sectors = DB::table('Sectors')->whereBetween('SectorID', [1, 10])->value('SectorID');
 return view('besttradesview', ['sectors10' => $sectors]);
} 

public function selectsubsector() //dropdown #2 not working
{
$subsectors = DB::table('Sectors')->where('parentid', $sectors)->get(); 
//this line is not working it does not recognize $sector variable
return view('besttradesview', ['subsectors42' => $subsectors]);
}

查看下拉列表#1:部门和#2:子部门

<form method="GET">
<div class="selectsector">
<Select class="selectsector" name = "sector">
@foreach($sectors10 as $sector) 
<option>{{ $sector->SectorName }}</option>
@endforeach
</select>

<Select class="selectsubsector" name = "subsector">
@foreach($subsectors42 as $subsector) 
<option>{{ $subsector->SectorName }}</option>
@endforeach
</select>
</form>

路线:

Route::get('kitysoftware/besttrades', 'SectorsController@selectsector');
Route::get('kitysoftware/besttrades', 'SectorsController@selectsubsector');

Getting error: Undefined variable: sectors

希望是你的要求:

<Select class="selectsector" onChange="getSelectorValue( this, '#selector2' )" id="selector1" name="sector">
    @foreach($sectors10 as $sector)
    <option>{{ $sector->SectorName }}</option>
    @endforeach
</select>

<Select class="selectsubsector" onChange="getSelectorValue( this, '#selector1' )" name = "subsector" id="selector2" >
    @foreach($sectors10 as $sector)
    <option>{{ $sector->SectorName }}</option>
    @endforeach
</select>

添加脚本使其工作:

<script type="text/javascript">
    function getSelectorValue( selectorObj, selector ){
        document.querySelector( selector ).value = selectorObj.value;
    }
</script>

好的,我设法使用 javascript 和 ajax 函数以及 json 数据类型来做到这一点。我是 JavaScript 的新人,这花了我一段时间,所以我要花时间为新人发布详细信息。我们开始吧:

视图文件: 诀窍是使用一个 html 隐藏对象来捕获路由 + 前缀,就像在下拉列表之前的这一行中:

 <input type="hidden" name="application_url" id="application_url" value="{{URL::to(Request::route()->getPrefix()) }}"/>

此对象的名称是 "application_url",稍后我们将在 javascript 代码中使用它来完成路由所需的 url。
名称为 "sectorSelect" 的 DropDown#1:

<label class="selectsector">Sector:</label>
<Select class="selectsector" id="sectorSelect" name="sectorSelect" >
    <option value=""> -- Please select sector --</option>
    @foreach ($sectors10 as $sector)
        <option value="{{ $sector->SectorID }}">{{ $sector->SectorName }}</option>
    @endforeach
</select>

下拉列表 #2 名称:"SubsectorSelect"

 <label class="selectsector">SubSector:</label>
 <Select class="selectsector" id="subSectorSelect" name="subSectorSelect">
    <option value=""> -- Select an option --</option> // you don't have to do nothing here since this will be populated it from a query depending on the dropdown#1 selected value
 </select>

现在在 web.php 路由文件中:

Route::get('kitysoftware/sectors/subsectors/{id}', 'SectorsController@selectsubsector');

我们正在创建一个带有 {id} 参数的路由。这将是下拉列表 #1 中的选定值。然后我们调用Sectorscontroller中的"selectsubsector"方法。

控制器: 第一个下拉查询:

public function selectsector()
{
$sectors = DB::table('Sectors')->select('SectorName', 'SectorID')- 
 >whereBetween('SectorID', [1, 10])->get();
    return view('besttradesview', ['sectors10' => $sectors]);

第二个下拉查询(selectsubsector 方法):

   public function selectsubsector($sectorId)
    {

    $subsectors = DB::table('Sectors')->select('SectorName', 'SectorID')->where('parentid', $sectorId)->get();
    return response()->json($subsectors); //this line it's important since we are sending a json data variable that we are gonna use again in the last part of the view.
    }

视图文件的最后一部分 javaScript + ajax 函数

<script type="text/javascript">
    $('#sectorSelect').change(function () { //we watch and execute the next lines when any value from the dropdown#1 is selected
        var id = $(this).val(); //we get the selected value on dropdown#1 and store it on id variable
        var url = $('#application_url').val(); //we get the url from our hidden element that we used in first line of our view file, and store it on url variable
            //here comes the ajax function part
            $.ajax({
            url: url + "/kitysoftware/sectors/subsectors/" + id, //we use the same url we used in our route file and we are adding the id variable which have the selected value in dropdown#1
            dataType: "json", //we specify that we are going to use json type of data. That's where we sent our query result (from our controller)
            success: function (data) { //*on my understanding using json datatype means that the variable "data" gets the value and that's why we use it to tell what to do since here.*
                //and this final part is where we use the dropdown#1 value and we set the values for the dropdown#2 just adding the variables that we got from our query (in controllert) through "data" variable.
                $('#subSectorSelect').empty();
                $.each(data, function (key, value) {
                    $('#subSectorSelect').append('<option value="' + key.SectorID + '">' + value.SectorName + '</option>');
                });
            }
        });
    });
</script>

希望对解答和解释有所帮助。我也很高兴得到一些反馈。

Controller

        public function selectsector() 
        { 
         $sectors = Sector::get();
         return view('besttradesview', compact('sectors'));
        } 
        
    public function selectsubsector($sectors)
        {
          $subsectors = Sectors::where('parentid', $sectors)->get(); 
        if (empty($subsectors)) {
            $html = '';
            $html = '<option value="">There has no Value</option>';
        } else {
            $html = '';
            foreach ($subsectors as $subsector) {
                $html .= '<option value="'.$subsector->id.'">'.$subsector->subsector.'</option>';
            }
        }
        return response()->json(['html' => $html]);       
        }

route

Route::get('/get-selector/{id}', 'Inventory\selectorController@selectsubsector')->name('get.selector');

ajax

$(document).on('change','.selectsector',function () { 
        var id= $(this).val();
        var url = "{{ URL::to('/get-selector') }}"+ '/' + id;
        $.ajax({
                url: url,
                type: 'get',
                dataType:'JSON',
                success: function (response) {
                    console.log(response);
                    if(response.html==''){
                        $('.selectsubsector').html('<option value="">There has no Value</option>');
                    }else{
                        $('.selectsubsector').html(response.html);
                    }   
                },error: function (exception) {
                    console.log(exception);
                }
            });
        });