从ajax表单中调用此路由器的findname,我需要处理该值并将其传递给另一个路由器,我无法弄明白该怎么做,这里是我如何尝试的示例:
#!/usr/bin/perl
use Mojolicious::Lite;
get '/foundname' => sub {
my $c = shift;
# Here I get the value from the form
my $name_on = $c->req->query_params->param('name');
if($name_on) {
# call another router and pass the name value to it
# It gives an error "Can't locate object method "get" ", I might not need to use "get", just don't know how to pass the value.
$c->get('/process_name')->to( searched => $name_on);
}
};
get '/process_name' => sub {
my $c = shift;
my $got_name = $c->req->query_params->param('searched');
...
};
谢谢!
答案 0 :(得分:1)
您需要在app
内的Mojolicious::Routes对象中查找路线。 lookup
的名称由Mojolicious :: Lite从URI的路径部分自动生成,因此/process_name
的名称为process_name
。
您返回Mojolicious::Routes::Route,其中有render
方法,您可以在那里传递参数。
use Mojolicious::Lite;
get '/foundname' => sub {
my $c = shift;
my $name_on = $c->req->query_params->param('name');
if( $name_on ) {
my $process_name = app->routes->lookup('process_name')->render( { searched => $name_on } );
$c->render( text => $process_name );
}
};
get '/process_name' => sub {
my $c = shift;
my $got_name = $c->req->query_params->param('searched');
$c->render( text => $got_name );
};
app->start;
当您卷曲时,您会将参数作为回复返回。
$ curl localhost:3000/foundname?name=foo
/process_name
然而,这可能不是正确的方法。如果要实现业务逻辑,则不应使用内部或隐藏路由。请记住,您的应用程序仍然只是Perl。你可以写一个sub
并调用它。
use Mojolicious::Lite;
get '/foundname' => sub {
my $c = shift;
my $name_on = $c->req->query_params->param('name');
if( $name_on ) {
my $got_name = process_name( $name_on );
$c->render( text => $got_name );
}
};
sub process_name {
my ( $got_name ) = @_;
# do stuff with $got_name
return uc $got_name;
};
app->start;
这将输出
$ curl localhost:3000/foundname?name=foo
FOO
这是更便携的方法,因为您可以轻松地对这些功能进行单元测试。如果你想拥有$c
,你必须传递它。您还可以在定义的任何app
中使用sub
关键字。
答案 1 :(得分:0)
对于原始问题,我会使用
$c->redirect_to()
有关传递变量的详细信息,请参阅此问题: Passing arguments to redirect_to in mojolicious and using them in the target controller
==
但是,我会更多地考虑编写潜艇(正如其他人所说)。 如果你有现有的逻辑,那么你可以将它包装在一个帮助器中,或者只是将逻辑放在帮助器中并调用它。
helper('process_name'=> sub{
my $self,$args = @_;
# Do some logic with $args->{'name'}
return $something;
});
get '/foundname' => sub {
my $c = shift;
my $name_on = $c->req->query_params->param('name');
if( $name_on ) {
my $process_name = $c->process_name({name => $name_on});
$c->render( text => $process_name );
}else{
$c->redner(text => 'Error',status=>500);
}
};