Laravel使用Ajax进行动态下拉

时间:2018-07-23 09:11:03

标签: javascript php jquery ajax laravel

我使用的是laravel 5.6,我的User表具有f_code的{​​{1}}外键,并且我有2个下拉列表,分别选择FacultyFaculty 。使用下拉菜单Programme将根据登录自动选择教师下拉菜单,而程序下拉列表将仅基于教师显示程序(我已经完成了2个表之间的关系)。我正在尝试使用ajax返回Auth::user()->f-codep_code并将它们附加到我的p_name下拉选择中,但是在下拉选择中未显示任何程序。有人可以帮助我吗?抱歉,如果我的问题有点令人困惑,我不确定我该如何正确地用语言解释,希望我的代码可以更好地解释。

任何帮助将不胜感激,谢谢您。

刀片视图

Programme

控制器

<!-- FACULTY -->
<select id="Faculty" class="form-control Faculty">
    <option value="0" disabled selected>Select Faculty</option>
    @foreach($FacultyList as $fac)
        <option value="{{$fac->f_code}}">{{$fac->f_name}}</option>
    @endforeach
</select>

<br>
<!-- PROGRAMME -->
<select id="Programme" class="form-control Programme">
    <option value="0" disabled selected>Select Programme</option>
</select>


<script type="text/javascript">

$(document).ready(function(){

    var lecturer_faculty = '{{ Auth::user()->f_code }}'
    var facSelect = document.getElementById("Faculty");
    facSelect.value = lecturer_faculty;

    var div=$(this).parent();
    var op=" ";


    $.ajax({
        type:'get',
        url:'{!!URL::to('findProgramme')!!}',
        data:{'id':facSelect.value},
        success:function(data){
            op+='<option value="0" selected disabled>Select Programme</option>';
            for(var i=0;i<data.length;i++){
                op+='<option value="'+data[i].p_code+'">'+data[i].programme_name+'</option>';
            }
            div.find('.Programme').html(" "); 
            div.find('.Programme').append(op); 

        },
        error:function(){

        }
    });
});
</script>

1 个答案:

答案 0 :(得分:0)

已解决

我不是动态使用ajax,而是在控制器内部选择Programme数据,并将其传递到视图中,并使用循环显示所有程序

刀片视图

<!-- FACULTY -->
<select id="Faculty" class="form-control Faculty">
    <option value="0" disabled selected>Select Faculty</option>
    @foreach($FacultyList as $fac)
        <option value="{{$fac->f_code}}">{{$fac->f_name}}</option>
    @endforeach
</select>

<br>
<!-- PROGRAMME -->
<select id="Programme" class="form-control Programme">
    <option value="0" disabled selected>Select Programme</option>
    @foreach($ProgrammeList as $prog)
        <option value="{{$prog->p_code}}">{{$prog->programme_name}}</option>
    @endforeach
</select>

<script type="text/javascript">

$(document).ready(function(){

    var lecturer_faculty = '{{ Auth::user()->f_code }}'
    var facSelect = document.getElementById("Faculty");
    facSelect.value = lecturer_faculty;
    facSelect.disabled = true;
});
</script>

控制器

function index()
{

    $FacultyList = Faculty::all();
    $ProgrammeList = Programme::select('p_code','programme_name')->where('faculty_id',Auth::user()->f_code)->take(100)->get();
    return View::make('generateqr',compact('FacultyList','ProgrammeList')); 
}


function findProgramme(Request $request)
{
    $data = Programme::select('p_code','programme_name')->where('faculty_id',$request->id)->take(100)->get();

    return response()->json($data);
}