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

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

你好 Whosebug 家庭。这是我的第一个问题,希望得到帮助。

我是 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 请求设置数据类型(如果你使用 jQuery)

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

然后按照以下方式尝试在您的控制器中使用

Request::json()

并查看结果

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

Request::get('userID')

首先使用您的 developer/network 工具(例如 firebug)检查您的 ajax 调用是否达到了预期的 controller/functions 并且参数是否正确转发。

在 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')
    }
});

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

您的 AJAX 正在 POSTing,但您没有设置 POST 路由,只有 GET。添加一个 POST 路由,像这样:

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

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

 $.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) {

            }
        });