简体   繁体   English

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

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

Hello StackOverflow family. 你好StackOverflow家族。 This is my very first question and I hope to get help. 这是我的第一个问题,我希望得到帮助。

I'm new to laravel framework and am using version 5.2 in my project. 我是laravel框架的新手,在我的项目中使用的是5.2版本。 Am trying to pass data using the post method from my ajax function to a particular controller method but no data is passed to the controller. 我试图使用post方法从我的ajax函数传递数据到特定的控制器方法,但没有数据传递给控制器​​。

I followed the steps in this forum https://laracasts.com/discuss/channels/laravel/process-data-in-controller-using-ajax-in-laravel but can't get it to work. 我按照这个论坛中的步骤https://laracasts.com/discuss/channels/laravel/process-data-in-controller-using-ajax-in-laravel但无法使其工作。 Here is what I've done so far. 这是我到目前为止所做的。

My JavaScript ( post_script.js ): 我的JavaScript( post_script.js ):

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

Note that this file is saved in assets/js directory in the laravel structure. 请注意,此文件保存在laravel结构的assets/js目录中。 Here is what I have in my route file ( routes.php ): 这是我在路由文件( routes.php )中的内容:

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

Here is the function I have in MyController.php file: 这是我在MyController.php文件中的函数:

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

In my view, I tried to access it like this: 在我看来,我试图像这样访问它:

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

Nothing is displayed! 什么都没显示! Please what am I doing wrong? 请问我做错了什么? I need your help. 我需要你的帮助。 Forgive me if my question is not proper but I hope you get what I mean. 如果我的问题不合适,请原谅我,但我希望你明白我的意思。 Thank you 谢谢

Your AJAX is POSTing, but you have no POST route set, only GET. 您的AJAX正在POST,但您没有设置POST路由,只有GET。 Add a POST route, like so: 添加POST路由,如下所示:

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

First check with your developer/network tool (eg. firebug) wether your ajax call reaches the desired controller/functions and that the parameters are forwarded correctly. 首先检查您的开发人员/网络工具(例如,firebug),你的ajax调用是否达到了所需的控制器/功能,并且参数是否正确转发。

A safe way to specify Url in the ajax call in the Laravel environment is using the URL facade like this: 在Laravel环境中在ajax调用中指定Url的安全方法是使用URL facade,如下所示:

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

In order to do it like this however you must store your js as a myscript.blade.php (!!) file and @include it into your view accordingly. 为了做到这一点,你必须将你的js存储为myscript.blade.php(!!)文件并将其包含在你的视图中。

For receiving your posted parameters in the controller function there is no need to declare function arguments, you can simply use the Input::Get() function eg. 为了在控制器函数中接收已发布的参数,不需要声明函数参数,只需使用Input :: Get()函数即可。 like this: 像这样:

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

If you try to do POST request you may need to have X-CSRF-Token . 如果您尝试执行POST请求,则可能需要使用X-CSRF-Token

Add this to meta: 将此添加到元:

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

And setup your AJAX: 并设置你的AJAX:

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

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

First you need set up dataType for ajax request like this (if you using jQuery) 首先,你需要像这样设置ajax请求的dataType(如果你使用jQuery)

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

then try use into your controller as follow 然后尝试使用您的控制器,如下所示

Request::json()

and see result 并看到结果

Also you may use Input::get() : 你也可以使用Input :: get():

Request::get('userID')

you can use route name to pass your data to the controller 您可以使用路由名称将数据传递给控制器

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

            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM