Mojolicious::Lite:如何在使用“redirect_to”时传递参数;
#!/usr/local/bin/perl
use warnings;
use 5.014;
use Mojolicious::Lite;
use DBI;
# ...
get '/choose' => sub {
my $self = shift;
my $lastname = $self->param( 'lastname' );
my $sth = $dbh->prepare( "SELECT id, firstname, birthday FROM $table WHERE lastname == ?" );
$sth->execute( $lastname );
my @rows;
while ( my $row = $sth->fetchrow_hashref ) {
push @rows, { id => $row->{id}, firstname => $row->{firstname}, lastname => $lastname, birthday => $row->{birthday} };
}
if ( not @rows ) {
$self->redirect_to( 'new_entry' );
} elsif ( @rows == 1 ) {
my $id = $rows[0]{id};
$self->redirect_to( "/show_address?id=$id" ); # show_address needs parameter "id"
} else {
$self->stash( rows => \@rows );
$self->render( 'choose' );
}
};
# ...
当我使用 redirect_to
时,除了直接在 url 中写入参数(“/show_address?id=$id”)之外,是否还有其他方法来传递参数?
#!/usr/local/bin/perl
use warnings;
use 5.014;
use Mojolicious::Lite;
use DBI;
# ...
get '/choose' => sub {
my $self = shift;
my $lastname = $self->param( 'lastname' );
my $sth = $dbh->prepare( "SELECT id, firstname, birthday FROM $table WHERE lastname == ?" );
$sth->execute( $lastname );
my @rows;
while ( my $row = $sth->fetchrow_hashref ) {
push @rows, { id => $row->{id}, firstname => $row->{firstname}, lastname => $lastname, birthday => $row->{birthday} };
}
if ( not @rows ) {
$self->redirect_to( 'new_entry' );
} elsif ( @rows == 1 ) {
my $id = $rows[0]{id};
$self->redirect_to( "/show_address?id=$id" ); # show_address needs parameter "id"
} else {
$self->stash( rows => \@rows );
$self->render( 'choose' );
}
};
# ...
When I use redirect_to
, is there another way to pass a parameter than writing it directly in the url ("/show_address?id=$id")?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
redirect_to 可以为您构建 url,并用您的参数替换路由中的占位符。
如果您需要使用参数构建 url,您可以执行以下操作:
另请注意,您可以通过设置 flash 变量来通过查询传递参数:
http://mojolicio.us/perldoc/Mojolicious/Controller#flash
该变量将被 Mojolicious 清理下一个请求。
redirect_to can build url for you and replace placeholders in your routes with your params.
If you need to build url with params you can do following:
Also note that you can pass parameters with query by setting flash variables:
http://mojolicio.us/perldoc/Mojolicious/Controller#flash
That variables will be cleaned up by Mojolicious with next request.