Laravel - check if Ajax request

后端 未结 11 830
梦谈多话
梦谈多话 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:12

    $request->wantsJson()

    You can try $request->wantsJson() if $request->ajax() does not work

    $request->ajax() works if your JavaScript library sets an X-Requested-With HTTP header.

    By default Laravel set this header in 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.

    But $request->wantsJson() will check the axios query without the need for a header 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
    

提交回复
热议问题