Laravel - check if Ajax request

后端 未结 11 797
梦谈多话
梦谈多话 2020-12-08 00:09

I have been trying to find a way to determine ajax call in Laravel but i don\'t find any document regarding it.

I have a index() function which i want t

相关标签:
11条回答
  • 2020-12-08 00:25
    if(Request::ajax()) 
    

    Looks to be the right answer. http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax

    0 讨论(0)
  • 2020-12-08 00:27

    Most of the answers are working fine. We can also check the request header

    request()->header('Accept')=='application/json'
    

    to check the request type

    0 讨论(0)
  • 2020-12-08 00:28

    For those working with AngularJS front-end, it does not use the Ajax header laravel is expecting. (Read more)

    Use Request::wantsJson() for AngularJS:

    if(Request::wantsJson()) { 
        // Client wants JSON returned 
    }
    
    0 讨论(0)
  • 2020-12-08 00:28
    public function index()
    {
        if(!$this->isLogin())
            return Redirect::to('login');
    
        if(Request::ajax()) // This is check ajax request
        {
          return $JSON;
        }
    
        $data = array();
        $data['records'] = $this->table->fetchAll();
    
        $this->setLayout(compact('data'));
    }
    
    0 讨论(0)
  • 2020-12-08 00:31

    Those who prefer to use laravel helpers they can check if a request is ajax using laravel request() helper.

    if(request()->ajax())
       // code
    
    0 讨论(0)
提交回复
热议问题