san*_*jha 2 php ajax fetch laravel
在我的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);
})
Run Code Online (Sandbox Code Playgroud)
在我的控制器中
public function loadData( Request $request )
{
if( $request->ajax() ) {
return $request->query('q');
}
return 'Not Ajax!';
}
Run Code Online (Sandbox Code Playgroud)
它总是返回“不是 Ajax!”;
我不确定为什么会这样。这不是一个问题,与其他图书馆喜欢jQuery或Axios
Request::ajax()检查X-Requested-With标题是否存在。
由于您使用的是 fetch,您必须手动将此标头添加到选项对象:
fetch(route, {
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
})
Run Code Online (Sandbox Code Playgroud)
例如,由于bootstrap.js 文件的设置方式,Axios 默认使用它。jQuery会自动为每个请求添加它,但跨域请求。