使用按钮onclick重定向



我使用的是Laravel框架和刀片模板引擎。

我想做的是,在我的视图中有两个按钮,当单击时会将您重定向到另一个视图。我尝试的代码是:

 <button type="button" onclick="{{ Redirect::to('users.index') }}">Button</button>

您可以尝试以下操作(假设此代码位于刀片模板中):

<button type="button" onclick="window.location='{{ url("users/index") }}'">Button</button>

然而,{{ url('users/index') }}将打印URL,因此,它在浏览器中会变成这样:

<button type="button" onclick="window.location='http://example.com/users/index'">Button</button>

这意味着你有一条这样声明的路线:

Route::get('users/index', array('uses' => 'UserController@index', 'as' => 'users.index'));

在这种情况下,也可以使用:

<button type="button" onclick="window.location='{{ route("users.index") }}'">Button</button>

输出将是相同的。

是的,您基本上需要使用URL助手来生成URL(就像只放一些类似的东西http://yoursite.com/users而不是PHP助手):

<button type="button" onclick="window.location='{{ URL::route('users.index'); }}'">Button</button>

虽然我不明白为什么你不能只使用"a href"标签而不是按钮,比如:

<a href="{{ URL::route('users.index'); }}">My button</a>

您还可以将href标记样式化为按钮。例如<a class="btn btn-primary" href="{{ route('users.create' }}">Create</a>这有助于避免混合javascript和blade指令。``

最新更新