我试图弄清楚如何在Laravel中使用ajax,jquery获得特定年份的所有主题。

我在数据库中有三个表:

years: id, name
subjects: id, name
year_subject: id, year_id , subject_id


这些是模型:

Year.php
Subject.php
YearSubject.php



  这是控制器中的功能


public function get_subjects($id)
{
   $sub = YearSubject::where("year_id", $id)->pluck("subject_id");
   $subjects=Subject::where('$id',$sub)->pluck('name','id');
        foreach($sub as $s)
        {
           $subjects= Subject::where('$id',$s)->pluck('name','id');
        }
   return json_encode($subjects);
}




  <script type="text/javascript">
       $(document).ready(function () {
         $('#grade').on('change', function () {
            var gradeID = $(this).val();
            $('#subject').empty();
            if (gradeID) {
              $.ajax({
                url: '{{url('get_subjects')}}' + '/' + gradeID,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (key, value) {
                    $('#subject').append('<option value="' + key + '">' + value + '</option>');
                       });
                    }
                 });
             } else {
                  $('#subject').empty();
              }
        });
     });
</script>

 <select  id="grade" name="grade" required>
     <option value="" disabled selected> Choose Year</option>
      @foreach($grades as $grade)
        <option value="{{$grade->id}}">{{$grade->name}}</option>
      @endforeach
</select>
<select  name="subject"  id="subject" >
   <option value="">Choose Subject </option>
</select>






  这是路线


Route::get('get_subjects/{id}', 'SubjectController@get_subjects')->name('get_subjects');


我猜错误是在控制器上。无法弄清楚如何在$ subjects处推送值。

最佳答案

将模型更改为如下所示-

Year.php

class Year extends Model{
    public $primaryKey = 'id';
    public $timestamps = true;
    protected $table = 'years';
    public function subjects(){
        return $this->belongsToMany('year_subject','year_id','subject_id');
    }
}


Subject.php

class Subject extends Model{
    public $primaryKey = 'id';
    public $timestamps = true;
    protected $table = 'subjects';

    public function years(){
        return $this->belongsToMany('year_subject','subject_id','year_id');
    }
}


您的控制器方法:

public function get_subjects($year_id){
    $subject_data = [];
    foreach(Year::where('id',$year_id)->subjects() as $each_subject_data){
        $subject_data[] = [
                'subject_id'   => $each_subject_data->id,
                'subject_name' => $each_subject_data->name
        ];
    }

    return response(json_encode($subject_data),200)
                                    ->header('Content-Type','application/json');
}


注意:您可以检查元素并在浏览器的“网络”选项卡中检查要接收的JSON,并相应地在控制器方法中修改所需的JSON格式。

关于javascript - Laravel,无法弄清楚如何通过下拉菜单显示特定年份的主题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52345580/

10-11 05:32