dongzha5934 2018-08-28 12:17
浏览 84
已采纳

Laravel ajax没有返回数据

I am having trouble retrieving data from Controller using ajax this is my code

the trigger

<select id="course_select" name="course_select" class="form-control" required autofocus value="{{old('course_select')}}" onchange="getCourse()">

The my ajax section

function getCourse(){
  var id=document.getElementById('course_select').value;
  alert(id);
  $.ajax({
    type:'get',
    url:'getCourseLessons/'+id,
    datatype:'json',
    success:function(data){
      console.log(data);
      alert(data.lessons);
    }
  });
}

and my controller

public function getCourseLessons($id){
      $lessons = DB::table('lessons')->select('id','Lesson_name')->where('course_id','=',$id)->get();
      return response()->json(array('lessons'=>$lessons));
}

Results console.log(data)

console.log(data)
ReferenceError: data is not defined[Learn More]

My Routes.

Route::get('/getcourselessons/{id}','AdminController@getCourseLessons');

I will appreciate all the help i can get.

  • 写回答

4条回答 默认 最新

  • douzhaxian1267 2018-08-28 12:59
    关注

    First of all please check the route you used in Route/Web.php it should be like this

    Route::get('getCourseLessons/{id}','YourController@getCourseLessons');
    

    Check the controller.

    public function getCourseLessons($id){
      $lessons = \DB::table('lessons')->select('id','Lesson_name')->where('course_id',$id)->get();
      return response()->json(array('lessons'=>$lessons));
    }
    

    As per your ajax code is ook but you can try this also.

    function getCourse(){
      var id=$('#course_select').val();
      alert(id);
         $.ajax({
           type:'get',
           url:'{{url('getCourseLessons')}}/'+id,
           datatype:'json',
           success:function(data){
               console.log(data);
               alert(data.lessons);
            }
         });
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 streamingtool
  • ¥15 MATLAB图像问题
  • ¥20 树莓派5做人脸情感识别与反馈系统
  • ¥15 selenium 控制 chrome-for-testing 在 Linux 环境下报错 SessionNotCreatedException
  • ¥15 使用pyodbc操作SQL数据库
  • ¥15 MATLAB实现下列
  • ¥30 mininet可视化打不开.mn文件
  • ¥50 C# 全屏打开Edge浏览器
  • ¥80 WEBPACK性能优化
  • ¥30 python拟合回归分析