链接到 Laravel 中的 Action Post 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40735551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:47:41  来源:igfitidea点击:

Link To Action Post Method in Laravel

laravel

提问by Sankar Smith

How will I pass variable to controller in POST method by link to action. This is my blade code

我将如何通过链接到操作将变量传递给 POST 方法中的控制器。这是我的刀片代码

{{ link_to_action('userviewController@getschoolbranch',$user->userId,['getid' => $user->userNo]) }}

These makes the url like http:://localhost/laravel/userview?getid=001 But I want to pass the variable in POST method from blade.

这些使 url 像 http:://localhost/laravel/userview?getid=001 但我想在 POST 方法中从刀片传递变量。

回答by Michel

If you want to do POSTfrom <a></a>you will have to do an AJAX post. Here's an example.

如果你想POST<a></a>你做一个 AJAX 帖子。这是一个例子。

HTML <a href="#" user-id="001">Get User</a>Notice the custom attribute user-id.

HTML <a href="#" user-id="001">Get User</a>注意自定义属性user-id

JAVASCRIPT (Jquery required)

JAVASCRIPT(需要 Jquery)

$('a[user-id]').click(function(){
 var user = $(this).attr('user-id');
$.ajax({
            url: '/get-user',
            type: 'POST',
            dataType: 'json',
            data: {userID: user},
            success: function(data){
                alert(data['success']);
            }
        });
return false;
});

ROUTE

路线

Route::post('/get-user', 'yourController@getUser');

CONTROLLER

控制器

public function getUser(Request $request){
  //Select from DB where userid = $request->input('userID');

//Return json to the AJAX success function
return response()->json(['success' => 'User found']);
}

Hope that help.

希望有所帮助。

回答by khany

You could also create a Form with just a submit button in it. Assuming you are using blade:

您还可以创建一个只有一个提交按钮的表单。假设您正在使用刀片:

<form method="post" action="{{ route('to.post.method', $user->userId) }}">
    <input type="hidden" name="getid" value="{{ $user->userNo }}">
    <input type="submit" name="submit" value="Link Text">
</form>

I haven't tested this and it also assumes your routes are set up to handle it but in theory it should work.

我还没有测试过这个,它也假设你的路线已经设置好来处理它,但理论上它应该可以工作。