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

时间:2018-11-30 04:01:00

标签: php ajax laravel drop-down-menu html-select

6,我正在使用一个下拉列表从数据库表中读取一列。我想要做的就是在该下拉列表上获取选定的值,并使用它创建一个新查询,并将其填充到新的下拉菜单中。

在阅读并查看了几个示例之后,我看到人们使用ajax,而其他人使用laravel HTTP请求(例如$request->get()),所以我不知道应该采取哪种方式,因为我对其中的任何一个都不熟悉,甚至什么时候尝试几次无法使其正常工作。

任何人都可以让我深入了解最佳/高效的方法吗?是否可以仅使用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');
  

获取错误:未定义变量:扇区

3 个答案:

答案 0 :(得分:3)

好吧,我设法使用json数据类型的javascript和ajax函数来做到这一点。我是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>

DropDown#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>

希望它有助于解决方案和解释。我也很高兴获得一些反馈。

答案 1 :(得分:1)

我希望这是您的要求:

<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>

答案 2 :(得分:0)

控制器

aws ecr get-login-password | docker login --username AWS --password-stdin MY-REGISTRY-URL

路线

        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]);       
        }

ajax

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