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

时间:2011-08-12 15:41:42

标签: perl redirect parameters mojolicious

#!/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”)?

1 个答案:

答案 0 :(得分:7)

redirect_to可以为您构建网址,并用您的参数替换路线中的占位符。

如果您需要使用参数构建网址,您可以执行以下操作:

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

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

Mojolicious将根据下一个请求清理这些变量。