截至目前,我的网站正在使用 jQuery Ajax 从前端向后端发出请求,然后后端通过检查 $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest" 来确定 ajax 请求。我正在尝试仅切换到本机 JS,并且想要使用 Fetch Api。问题是我似乎无法检测 PHP 中的 fetch api 请求与常规页面加载请求。 $_SERVER['HTTP_X_REQUESTED_WITH'] 显然不再起作用了。所以我尝试设置新的标头({HTTP_X_REQUESTED_WITH})。然后还是不行。感谢任何帮助,谢谢
JS:
let dataForm = new FormData(),
reqHeaders = new Headers({
"X-Custom-Header": "ThisMeansAjaxRequest",
});
dataForm.append('postFavColor', 'green');
let result = fetch('/ajax/', {
method: 'POST',
header: reqHeaders,
body: dataForm
})
.then(res=>{
if('json' in res){
return res.json()
}
throw new Error('Not so JSON');
})
.then(res=>{
if (res.status === 'success') {
// WE MADE IT!!!
console.log(req);
return res.message
}
else{
throw new Error('Server returned Error', res)
}
})
.catch(err=>{
console.error('fetch error of some sort', err);
});
PHP:
// Below if statment was being used for Ajax request test from jQuery
// replacing the if statement below with the custom header passed from fetch api
// still doesn't work. Tried all 4 versions below
// if (isset($_SERVER['X_Custom_Header']) && $_SERVER['X_Custom_Header']=="ThisMeansAjaxRequest")
// if (isset($_SERVER['Custom_Header']) && $_SERVER['Custom_Header']=="ThisMeansAjaxRequest")
// if (isset($_SERVER['HTTP_X_Custom_Header']) && $_SERVER['HTTP_X_Custom_Header']=="ThisMeansAjaxRequest")
// if (isset($_SERVER['HTTP_Custom_Header']) && $_SERVER['HTTP_Custom_Header']=="ThisMeansAjaxRequest")
//// Original jquery Ajax detector
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") {
//continue;
//echo 'This is certified Ajax request <br>';
$data = array(
'status' => 'success',
'message' => 'You\'re a Wizzard Harry!'
);
echo json_encode($data);
}
else{
//Not ajax request so display page
header("location: www.example.com/index.php");
}
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)