【问题标题】:`$request->ajax()` does not detect ajax request when using Fetch API to pull data in Laravel在 Laravel 中使用 Fetch API 拉取数据时,`$request->ajax()` 未检测到 ajax 请求
【发布时间】:2020-09-18 00:18:30
【问题描述】:

在我的Laravel 应用程序中,我使用Fetch API 在滚动上加载数据。下面是我在刀片文件中的JS 代码

let route = '{{ route("load") }}' + '?q=' + encodeURI('{{ $para }}');
fetch(route)
.then(response => {
   if(!response.ok) {
       throw new Error('Network response was not ok');
   }
   return response.text();
})
.then(data => {                       
   console.log(data);                       
})
.catch((error) => {
   console.error('Error:', error);
})

在我的控制器中

public function loadData( Request $request )
{
    if( $request->ajax() ) {

       return $request->query('q');

     }
     return 'Not Ajax!';
}

它总是返回 'Not Ajax!';

我不确定为什么会这样。 jQueryAxios 等其他库没有问题

【问题讨论】:

    标签: php ajax laravel fetch


    【解决方案1】:

    Request::ajax() 检查X-Requested-With 标头是否存在。

    由于您使用的是 fetch,因此您必须手动将此标头添加到 options object

    fetch(route, {
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      },
    })
    

    例如,由于bootstrap.js file is set up. jQuery adds it automatically 用于除跨域请求之外的每个请求。

    【讨论】:

    【解决方案2】:

    请尝试使用 request()->ajax() 函数代替 $request->ajax()。我认为问题是您在顶部导入了错误的请求。这也发生在我身上,因为编辑器

    【讨论】:

    • 不工作。我认为 $request 是正确的,因为如果删除 ajax 检查,我可以看到 $request->query('q') 值。
    【解决方案3】:

    在方法中使用“return”时要小心。尝试将 return 'Not Ajax!' 括起来;否则

    else{
        return 'Not Ajax!';
    }
    

    【讨论】:

    • 他为什么要小心?如果条件为真,则返回后将不执行任何操作(因为返回了某些内容)。你的 else 将产生与没有 else 的函数完全相同的结果。 FriendsOfPHP 的代码样式修复程序中甚至还有一个 rule for that,名为 no_useless_else
    猜你喜欢
    • 2018-02-28
    • 2018-10-18
    • 2018-08-30
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多