Laravel 4 Ajax check to include XMLHttpRequest (from Magnific Popup)

吃可爱长大的小学妹 提交于 2019-12-19 04:23:21

问题


Using the code from this question,

@extends('layouts.' . isset($ajax) ? 'ajax' : 'master')

to check for Ajax. It works for regular Ajax page loads but not when using a popup.

In this case I'm using Magnific Popup's Ajax mode, the request header is XMLHttpRequest but Laravel returns the non-ajax (extended) layout.


回答1:


First of all I don't know how the $ajax variable is being set(isset($ajax)), but the right way to check for an ajax request in Laravel is

if(Request::ajax()) {
    // ...
}

Or, short form (using ternary operator in a single expression)

$ajax = Request::ajax() ? true : false;

So, according to your link of another answer, this should work

@extends(((Request::ajax()) ? 'layouts.ajax' : 'layouts.master'))

How this works ?

In vendor\laravel\framework\src\Illuminate\Http there is a Request.php class you can see

/**
 * Determine if the request is the result of an AJAX call.
 * 
 * @return bool
 */
public function ajax()
{
    return $this->isXmlHttpRequest();
}

Here isXmlHttpRequest() is an extended method from Request.php class of Symphony, because Laravel's Request class extends Symfony\Component\HttpFoundation\Request.php and in this class there is the main method which determines the ajax request by

public function isXmlHttpRequest()
{
    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}

So, if X-Requested-With request header is set then it's an ajax request and if this header is not sent then it's not an ajax request. So, the question is how isset($ajax) is being set and if it's set by you then the jQuery library you are using it is not doing it but it's sending X-Requested-With request header instead and in this case you should use Laravel's Request::ajax() method to determine the ajax request.

BTW, I would prefer to use a completely different view for ajax request which doesn't extend master layout. You may like this Detect Ajax Request-Php And Frameworks.



来源:https://stackoverflow.com/questions/20166320/laravel-4-ajax-check-to-include-xmlhttprequest-from-magnific-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!