在我的 Laravel
应用程序中,我使用 Fetch API
来加载滚动数据。下面是我在 Blade 文件中的 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);
})
在我的 Controller 中
public function loadData( Request $request )
{
if( $request->ajax() ) {
return $request->query('q');
}
return 'Not Ajax!';
}
它总是返回 'Not Ajax!';
我不确定为什么会这样。 jQuery
或 Axios
最佳答案
Request::ajax()
检查 X-Requested-With
header 是否存在。
由于您使用的是 fetch,因此您必须手动将此 header 添加到 options object :
fetch(route, {
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
})
例如,Axios 默认使用它,因为 bootstrap.js file is set up . jQuery adds it automatically除了跨域请求之外的每个请求。
关于php - `$request->ajax()` 在Laravel中使用Fetch API拉取数据时没有检测到ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62102726/