简体   繁体   English

Laravel - 检查是否有 Ajax 请求

[英]Laravel - check if Ajax request

I have been trying to find a way to determine ajax call in Laravel but i don't find any document regarding it.我一直试图找到一种方法来确定 Laravel 中的 ajax 调用,但我没有找到任何关于它的文档。

I have a index() function which i want to handle situation differently based on the nature of request.我有一个index()函数,我想根据请求的性质以不同的方式处理情况。 Basically this is a resource controller method that is bound to GET request.基本上这是一个绑定到 GET 请求的资源控制器方法。

public function index()
    {
        if(!$this->isLogin())
            return Redirect::to('login');

        if(isAjax()) // This is what i am needing.
        {
          return $JSON;
        }

        $data = array();
        $data['records'] = $this->table->fetchAll();

        $this->setLayout(compact('data'));
    }

I know the other methods of determining the Ajax request in PHP but i want something specific to Laravel.我知道在 PHP 中确定 Ajax 请求的其他方法,但我想要一些特定于 Laravel 的方法。

Thanks谢谢

Updated:更新:

I tried using我尝试使用

 if(Request::ajax())
    {
        echo 'Ajax';
    }

But i am receiving error : Non-static method Illuminate\\Http\\Request::ajax() should not be called statically, assuming $this from incompatible context但我收到错误: Non-static method Illuminate\\Http\\Request::ajax() should not be called statically, assuming $this from incompatible context

The class shows that this is not a static method.该类表明这不是静态方法。

Maybe this helps.也许这有帮助。 You have to refer the @param你必须参考@param

         /**       
         * Display a listing of the resource.
         *
         * @param  Illuminate\Http\Request $request
         * @return Response
         */
        public function index(Request $request)
        {
            if($request->ajax()){
                return "AJAX";
            }
            return "HTTP";
        }

To check an ajax request you can use if (Request::ajax())要检查 ajax 请求,您可以使用if (Request::ajax())

Note: If you are using laravel 5, then in the controller replace注意:如果您使用的是 Laravel 5,则在控制器中替换

use Illuminate\Http\Request;

with

use Request; 

I hope it'll work.我希望它会起作用。

You are using the wrong Request class.您使用了错误的Request类。 If you want to use the Facade like: Request::ajax() you have to import this class:如果你想像这样使用 Facade: Request::ajax()你必须导入这个类:

use Illuminate\Support\Facades\Request;

And not Illumiante\\Http\\Request而不是Illumiante\\Http\\Request


Another solution would be injecting an instance of the real request class:另一种解决方案是注入真实请求类的实例:

public function index(Request $request){
    if($request->ajax()){
        return "AJAX";
    }

(Now here you have to import Illuminate\\Http\\Request ) (现在你必须导入Illuminate\\Http\\Request

$request->wantsJson() $request->wantsJson()

You can try $request->wantsJson() if $request->ajax() does not work如果$request->ajax()不起作用,您可以尝试$request->wantsJson()

$request->ajax() works if your JavaScript library sets an X-Requested-With HTTP header.如果您的 JavaScript 库设置了 X-Requested-With HTTP 标头,则$request->ajax()有效。

By default Laravel set this header in js/bootstrap.js默认情况下,Laravel 在 js/bootstrap.js 中设置这个头文件

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

In my case, I used a different frontend code and I had to put this header manually for $request->ajax() to work.就我而言,我使用了不同的前端代码,并且必须手动放置此标头才能使$request->ajax()工作。

But $request->wantsJson() will check the axios query without the need for a header X-Requested-With :但是$request->wantsJson()将检查 axios 查询而不需要头X-Requested-With

// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or 
\Request::wantsJson() // not \Illuminate\Http\Request

For those working with AngularJS front-end, it does not use the Ajax header laravel is expecting.对于那些使用AngularJS前端的人来说,它不使用 laravel 期望的 Ajax 标头。 ( Read more ) 阅读更多

Use Request::wantsJson() for AngularJS:对 AngularJS 使用Request::wantsJson()

if(Request::wantsJson()) { 
    // Client wants JSON returned 
}

Those who prefer to use laravel helpers they can check if a request is ajax using laravel request() helper.那些喜欢使用 laravel helper 的人可以使用 laravel request() helper 检查请求是否是 ajax。

if(request()->ajax())
   // code
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'));
}

有时Request::ajax()不起作用,然后使用\\Request::ajax()

after writing the jquery code perform this validation in your route or in controller.编写 jquery 代码后,在您的路由或控制器中执行此验证。

$.ajax({
url: "/id/edit",
data:
name:name,
method:'get',
success:function(data){
  console.log(data);}
});

Route::get('/', function(){
if(Request::ajax()){
  return 'it's ajax request';}
});

Most of the answers are working fine.大多数答案都运行良好。 We can also check the request header我们还可以检查请求头

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

to check the request type检查请求类型

Do something like this
public function functionName(User $user): string
{
    (string) $message = "";
    // check if request is ajax
    if(request()->ajax())
    {
        if($this->isOwner($user->id)){
            $message = 'success';
        }else{
            $message = "You are unauthorized to perform this action.";
        }
    }else{
        $message = 'Wrong server request';
    }
    return $message;        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM