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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53551050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:11:11  来源:igfitidea点击:

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

phpajaxlaraveldrop-down-menuhtml-select

提问by gallo2000sv

6, I'm using a dropdown to read a column from a database table. All I want is to get the selected value on that dropdown and use it to create a new query that will be populated in a new drop-down.

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

After reading and see several examples I see people using ajax and other people using laravel HTTP request like $request->get()so i don't know which way to take since I'm not familiar with any of those and even when trying several times can't get it to work.

阅读并查看几个示例后,我看到有人使用 ajax 和其他人使用 laravel HTTP 请求,$request->get()所以我不知道采取哪种方式,因为我不熟悉其中任何一种,即使尝试多次也无法获得它上班。

Can anyone give me an insight into the best/efficient way to do it? Is it possible to do it only using php or some feature in laravel that I'm missing?

任何人都可以让我深入了解最好/最有效的方法吗?是否可以仅使用 php 或我缺少的 laravel 中的某些功能来完成此操作?

Here is my controller:

这是我的控制器:

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

View with dropdow #1: sector and #2: subsector

使用下拉菜单查看 #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>

Routes:

路线:

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

Getting error: Undefined variable: sectors

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

回答by gallo2000sv

Ok, i managed to do it using javascript and ajax function with json datatype. I'm new at JavaScript and it took me a while so i'm taking the time to publish the details for the newcomers. Here we go:

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

The View file:The trick is to use a html hidden object that captures a route + prefix like in this line before the dropdowns:

视图文件:诀窍是使用一个 html 隐藏对象,在下拉菜单之前捕获路由 + 前缀,如这一行:

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

The name of this object is "application_url" which we'll be using later in the javascript code to complete the url that the routes needs.
DropDown#1 with name "sectorSelect":

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

<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 with name: "SubsectorSelect"

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>

Now in the web.php routes file:

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

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

We are creating a route with an {id} parameter. This will be the selected value in dropdown #1. Then we call the "selectsubsector" method in the Sectorscontroller.

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

Controller:First dropdown query:

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

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

Second Dropdown query (selectsubsector method):

第二个下拉查询(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.
    }

Final part of the view fileThe javaScript + ajax function

视图文件最后一部分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>

Hope it helps the solution and the explanations. I'm happy to get some feedback as well.

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

回答by Vinesh Goyal

I hope it is your requirement:

我希望这是您的要求:

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

Add Script to make it work:

添加脚本以使其工作:

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