【问题标题】:Send a value from html to Routes in Laravel将值从 html 发送到 Laravel 中的路由
【发布时间】:2017-09-21 19:51:20
【问题描述】:

我想知道如何将值从 html 文件发送到 laravel 中的 routes.php 文件。这是我的html:

<h1 id="title"  name="otherUser" value="{{session()->get('user2')}}">{{session()->get('user2')}}</h1>

这是我的 php:

Route::post('commendUser', function(Request $request) {
    $data = $request->all();
    $username = /*FIXME*/ ;
    echo($username);
});

谁能解释如何正确地将用户名值从 html 获取到路由?谢谢!

杰克

【问题讨论】:

    标签: php html laravel laravel-5 laravel-4


    【解决方案1】:

    您可以使用 name 属性从 html 中获取任何值:

    $username = $request->otherUser;
    
    or :
    
    $username = $request->input('otherUser');
    
    or using a global helper:
    
    $username = request('otherUser');
    
    or using Input facade :
    
    $username = Input::get('otherUser');
    

    然而您需要使用 post 方法而不是 h1 标签来设置表单,例如:

    <form action="/commendUser" method="post">
        {{ csrf_field() }}
        <input type="text" name="otherUser" value="{{session()->get('user2')}}">
        <button type="submit">Submit</button>
    </form>
    

    在您的路线中,您可以使用dd($username) 而不是回显它。

    更新

    您还需要在 web.php 文件的顶部导入 Request 外观,如下所示:

    use Illuminate\Http\Request;
    
    Route::post('commendUser', function(Request $request) {
        dd($request->input('otherUser'));
    });
    

    还有

    任何指向POST、PUT 或DELETE 路由的 HTML 表单都应包含在 Web 路由文件中定义的 CSRF 令牌字段。否则,请求将被拒绝。您可以在CSRF documentation 中阅读有关CSRF 保护的更多信息,因此我已将其添加到表单中:

    如果

    你仍然得到一个空值,这可能是错误的 会话值。

    【讨论】:

    • 你能解释一下 HTML 会是什么样子吗?我还是有点迷茫……
    • 我已经更新了我的答案,检查一下,如果有不清楚的地方告诉我。
    • 当我这样做时它显示为 null。
    【解决方案2】:

    您没有正确使用 HTML 标签,H1 不是用于发送数据的表单域。改为使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多