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 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题