如何从 laravel 中的 ajax 请求获取数据

how to get data from ajax request in laravel

我正在执行 ajax 请求并传递此数据

    $.ajax({
  url: "{{URL::to('match')}}/"+ id,
  type: 'PUT',
  // dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
  data: {
    match_id : id,
    start_time : newTime,
    competitionId: {{$cid}},
    _token:     '{{ csrf_token() }}'
  }
})

并在 laravel 中尝试将此数据作为

dd($request->start_time);

但它不起作用我得到空值

在 chrome 开发者工具中 正确发送 ajax 请求的数据这是一个简单的

match_id:1
start_time:03:00
competitionId:1
_token:9p8plPay7HLvJvMrTgxayEH74Ow6c2D1cli1yU01

在我将此站点移至新服务器之前,所有这些都运行良好

我错过了什么文件吗?

输入phpartisanroute:list

检查你在那里的路线,例如你的

方法=放

Uri = 匹配/{匹配}

姓名=match.update

Action = App\Http\Controllers\MatchController@update //你的方法

路线:

Route::resource('/match', 'MatchController');

这是您的 ajax 电话:

$.ajax({
    url: 'match/'+ id, //this is your uri
    type: 'PUT', //this is your method
    data: { match_id:id, start_time:newTime },
    dataType: 'json',
    success: function(response){

    }
});

您的控制器:

public function update(Request $request, $match_id)
{
   if(request()->ajax()){
      $match = Match::find($match_id);
      $validator = Validator::make($request->all(), [
         'start_time'=>'required',
      ]);

      if($validator->passes()) 
      {
        $match->start_time = $request->start_time;
        $match->save();

        return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
      }
      return response()->json(['msg'=>$validator->errors()->all()]);
    }
}

在我将类型更改为 Post 然后添加字段 _method: PUT 后,它工作正常 即

$.ajax({
      url: "{{URL::to('match')}}/"+ id,
      type: 'POST',
      // dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
      data: {
        _method: 'PUT',
        match_id : id,
        start_time : newTime,
        competitionId: {{$cid}},
        _token:     '{{ csrf_token() }}'
      }
    })