perl – Mojolicious :: Lite:使用“redirect_to”时如何传递参数;

前端之家收集整理的这篇文章主要介绍了perl – 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”)?

解决方法

redirect_to可以为您构建url,并使用params替换路由中的占位符.

如果您需要使用params构建url,您可以执行以下操作:

my $url = $self->url_for("/show_address");
$self->redirect_to($url->query(id => $id));

另请注意,您可以通过设置flash变量来传递带有查询的参数:
http://mojolicio.us/perldoc/Mojolicious/Controller#flash

MojolicIoUs将根据下一个请求清理这些变量.

原文链接:https://www.f2er.com/Perl/172216.html

猜你在找的Perl相关文章