laravel中ajax 非同步載入資料,選擇對應的學校對應的專業

listenon發表於2018-06-26

html程式碼:laravel中ajax 非同步載入資料,選擇對應的學校對應的專業

js程式碼:

$('#school').change(function () {
    var school_id = $(this).val();
    $.ajax({
        url: "http://hbcrjyw.test/online/school",
        type: "get",
        dataType: "json",
        data: {school_id: school_id},
        success: function (data) {
            // console.log(data);
            $('#major').html('<option value="">請選擇專業</option>');
            $.each(data, function (i, item) {
                $("#major").append("<option value='" + item.id + "'>" + item.name + "</option>");
            });
        }
    })
});複製程式碼

控制器程式碼:

/**
 * 報名頁面
 */
public function edit(Request $request, $id)
{
    //查出所有學校
    $schools = School::with('majors')->get();
    //查出所選擇的專業
    $major_id = $request->major_id;
    $first_major = Major::with('school')->find($major_id);
    //查出學校下的專業
    $first_school = School::with(['majors' => function ($query) {
        $query->orderBy('grade');
    }])->find($id);

    return view('home.online.edit', compact('schools', 'first_major', 'first_school'));
}

/**
 * 查出所有學校對應的專業
 */
public function school(Request $request)
{
    $school_id = $request->school_id;
    $majors = Major::where('school_id', $school_id)->orderBy('grade')->get();
    echo json_encode($majors);
}
路由:
Route::group(['prefix' => 'online'], function () {
    Route::get('school', 'OnlineController@school')->name('online.school');
});
Route::resource('online', 'OnlineController');
複製程式碼


相關文章