MAO-EYE 2019-03-06 07:22 采纳率: 100%
浏览 32

Laravel Ajax下拉示例

can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax. i have done it without ajax, but i don't know how to do with ajax. without ajax:

<select name="nation_id" class="custom-select" >
    <option selected value=" ">Choose...</option>
    @foreach($nations as $nations)
    <option value="{{@$nation_id}}"  {{@$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{@$nations->nation}}</option>
@endforeach

Controller:

$nations = nation::all();
  • 写回答

2条回答 默认 最新

  • DragonWar% 2019-03-06 08:13
    关注

    Create a route for your method which will fetch all the nations-

    Route::get('nations-list', 'YourController@method');
    

    Create a method in your controller for the above route-

    public function method()
    {
        $nations = Nation::all()->pluck('nation', 'id');
    
        return response()->json($nations)
    }
    

    Add a select box like this in your HTML-

    <select id="nation_id" name="nation_id"></select>
    

    If you want to auto select the option based on a variable then you can do this-

    <input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
    

    And then add this script in your HTML to fetch the nation list on page load-

    <script>
    $(document).ready(function($){
        $.get('nations-list', function(data) {
            let teacher_nation_id = $('#teacher_nation_id').val();
            let nations = $('#nation_id');
            nations.empty();
    
            $.each(data, function(key, value) {
                nations.append("<option value='"+ key +"'>" + value + "</option>");
            });
    
            nations.val(teacher_nation_id); // This will select the default value
        });
    });
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入