如何通过post方法将数据从ajax传递到laravel 5.2控制器


How to pass data from ajax to laravel 5.2 controller via post method

Hello StackOverflow family.这是我的第一个问题,我希望得到帮助。

我是 laravel 框架的新手,在我的项目中使用 5.2 版。我尝试使用 post 方法将数据从我的 ajax 函数传递到特定的控制器方法,但没有数据传递到控制器。

我按照这个论坛中的步骤操作 https://laracasts.com/discuss/channels/laravel/process-data-in-controller-using-ajax-in-laravel 但无法让它工作。这是我到目前为止所做的。

我的JavaScript ( post_script.js ):

$.ajax({
    method: 'POST',
    url: './home',
    data: {
        userID: 76,
        userName: 'Jimmy'
     },
});

请注意,此文件保存在 laravel 结构assets/js目录中。这是我的路由文件(routes.php

):
Route::get('/', "MyController@home");
Route::get('home', "MyController@home");

这是我MyController.php文件中的功能:

function home(Request $request) {
    $userID = $request['userID'];
    $userName = $request['userName'];
    return view('home', [
      'userID'=> $userID,
      'userName' => $userName
    ]);
}

在我看来,我试图像这样访问它:

<p>User ID: {{$userID}}</p>
<p>User Name: {{$username}}</p>

不显示任何内容!请问我做错了什么?我需要你的帮助。如果我的问题不合适,请原谅我,但我希望你明白我的意思。谢谢

你的 AJAX 正在发布,但你没有设置发布路由,只有 GET。 添加 POST 路由,如下所示:

Route::post('home', "MyController@home");

首先检查您的开发人员/网络工具(例如Firebug)是否到达所需的控制器/函数,并且参数是否正确转发。

在Laravel环境中的ajax调用中指定URL的一种安全方法是使用URL外观,如下所示:

url: "{{ URL::to('home'); }}",

但是,为了做到这一点,您必须将js存储为myscript.blade.php(!!)文件,并相应地将其@include到视图中。

为了在控制器函数中接收您发布的参数,无需声明函数参数,您可以简单地使用 Input::Get() 函数,例如:

public function home()
{
  $userID = Input::Get('userID');
  $userName = Input::Get('userName');
  return view('home', [ 'userID'=> $userID, 'userName' => $userName ]);
}

如果您尝试执行 POST 请求,您可能需要X-CSRF-Token .

将此添加到元:

<meta name="csrf-token" content="{{ csrf_token() }}">

并设置您的 AJAX:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

在拉拉维尔文档中:https://laravel.com/docs/5.2/routing#csrf-x-csrf-token

首先,您需要像这样为 ajax 请求设置 dataType(如果您使用 jQuery)

 $.ajax({
    method: 'POST',
    url: './home',
    dataType: 'json'
    data: {
        userID: 76,
        userName: 'Jimmy'
     },
})

然后尝试按如下方式在控制器中使用

Request::json()

并查看结果

您也可以使用 Input::get() :

Request::get('userID')

您可以使用路由名称将数据传递给控制器

 $.ajaxSetup({
            headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
        });
        $.ajax({
            type:'POST',
            url: '{{route("route_name_with_post_method")}}',
            data:{
              'id': data
            },
            success:function(r){
            },error:function(r) {
            }
        });