douhui3305 2013-11-23 18:41
浏览 91

Laravel 4 Ajax检查包括XMLHttpRequest(来自Magnific Popup)

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条回答 默认 最新

  • duankanjian4642 2013-11-23 20:39
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序