質問

I'm trying to make a small webapp to control the command-line music player I use (mocp), but I'm having trouble hitting routes when the user presses a button on the page. I expect the problem is related to my lack of HTML.

Code:

#!/usr/bin/perl
use Mocp;
use Mojolicious::Lite;

my $mocp = Mocp->new;

for my $action ( qw( play pause stop next previous unpause toggle-pause server ) ) {
    get $action => sub {
        my $self = shift;
        $mocp->$action;
        $self->render( 'controls' );
    };
}

get '/' => sub { shift->render( 'controls' ) };
app->start;

__DATA__

@@ controls.html.ep 

%= input_tag 'play', type => 'button', value => 'Play'
%= input_tag 'pause', type => 'button', value => 'Pause'
%= input_tag 'volup', type => 'button', value => 'Volume Up'
%= input_tag 'voldown', type => 'button', value => 'Volume Down'
%= input_tag 'toggle', type => 'button', value => 'Toggle'
%= input_tag 'next', type => 'button', value => '>>'
%= input_tag 'previous', type => 'button', value => '<<'

If I navigate to the routes directly (e.g. '/play'), everything works as expected. The goal is to simply click the 'Play' button to execute the associated method, rather than having to type the route out by hand. My questions at this stage are:

  1. Is mapping these methods to routes the best way to go about this?
  2. If so, how do I trigger a route with an 'onclick' button event as in JavaScript?

Any advice is much appreciated.

役に立ちましたか?

解決

Using jQuery on client side you can trigger route with $.get() function

%= input_tag 'play', type=>'button', value=>'Play', onclick=>"$.get('/play')"

or

<input type="button" value="Play" onclick="$.get('/play');">

To use jQuery you have to add the following line into your template

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top