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

发布于 2024-11-29 10:35:11 字数 998 浏览 0 评论 0原文

#!/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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦与时光遇 2024-12-06 10:35:11

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

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

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

另请注意,您可以通过设置 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:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文