0

从 ajax 表单调用该路由器 foundname,我需要处理该值并将其传递给另一个路由器,我不知道该怎么做,这是我尝试的示例:

#!/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');
   ...
 };

谢谢!

4

2 回答 2

1

你需要通过你的Mojolicious::Routes对象在你的app. 的名称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

于 2017-02-23T16:30:39.117 回答
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);
    }
};
于 2017-02-26T22:55:49.037 回答