diff --git a/Changes b/Changes index 0d44e55cd8..1f49d16dd2 100644 --- a/Changes +++ b/Changes @@ -11,6 +11,7 @@ This file documents the revision history for Perl extension Mojolicious. - Added finished callback support for HTTP transactions. - Added relative path support to Mojo::URL. (marcus) - Added simple iterator support to Mojo::DOM. + - Added is_xhr method to Mojo::Message::Request. - Improved Mojo::Client error logging. - Improved Mojo::Template error messages. - Improved generated multipart messages to be 2 bytes shorter. diff --git a/lib/Mojo/Message/Request.pm b/lib/Mojo/Message/Request.pm index bb135eabf6..4c000bb132 100644 --- a/lib/Mojo/Message/Request.pm +++ b/lib/Mojo/Message/Request.pm @@ -98,6 +98,19 @@ sub is_secure { return; } +sub is_xhr { + my $self = shift; + + # No ajax + return unless my $with = $self->headers->header('X-Requested-With'); + + # Ajax + return 1 if $with =~ /XMLHttpRequest/i; + + # No ajax + return; +} + sub param { my $self = shift; $self->{_params} = $self->params unless $self->{_params}; @@ -487,6 +500,12 @@ Make sure message has all required headers for the current HTTP version. Check if connection is secure. +=head2 C + + my $xhr = $req->is_xhr; + +Check C header for C value. + =head2 C my $param = $req->param('foo'); diff --git a/t/mojolicious/lite_app.t b/t/mojolicious/lite_app.t index ac52f5c2d3..acf008a022 100644 --- a/t/mojolicious/lite_app.t +++ b/t/mojolicious/lite_app.t @@ -16,7 +16,7 @@ use Test::More; # Make sure sockets are working plan skip_all => 'working sockets required for this test!' unless Mojo::IOLoop->new->generate_port; -plan tests => 419; +plan tests => 429; # Pollution 123 =~ m/(\d+)/; @@ -58,6 +58,13 @@ get '/null/:null' => sub { $self->render(text => $self->param('null'), layout => 'layout'); }; +# GET /maybe/ajax +get '/maybe/ajax' => sub { + my $self = shift; + return $self->render(text => 'is ajax') if $self->req->is_xhr; + $self->render(text => 'not ajax'); +}; + # GET /stream get '/stream' => sub { my $self = shift; @@ -487,6 +494,16 @@ $t->get_ok("http://sri:foo\@localhost:$port/stream")->status_is(200) ->header_is('X-Powered-By' => 'Mojolicious (Perl)') ->content_like(qr/^foobarsri\:foohttp:\/\/localhost\:\d+\/stream$/); +# GET /maybe/ajax (not ajax) +$t->get_ok('/maybe/ajax')->status_is(200) + ->header_is(Server => 'Mojolicious (Perl)') + ->header_is('X-Powered-By' => 'Mojolicious (Perl)')->content_is('not ajax'); + +# GET /maybe/ajax (is ajax) +$t->get_ok('/maybe/ajax', {'X-Requested-With' => 'XMLHttpRequest'}) + ->status_is(200)->header_is(Server => 'Mojolicious (Perl)') + ->header_is('X-Powered-By' => 'Mojolicious (Perl)')->content_is('is ajax'); + # GET /finished (with finished callback) $t->get_ok('/finished')->status_is(200) ->header_is(Server => 'Mojolicious (Perl)')