问题
As of right now my site is using jQuery Ajax to make a request from front end to back end and then the backend determines the ajax request by checking for $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest". I'm trying to switch over to native JS only, and want to use the Fetch Api. Problem is I can't seem to detect the fetch api request in PHP vs regular page load request. $_SERVER['HTTP_X_REQUESTED_WITH'] obviously doesn't work anymore. So I tried to set new Header({HTTP_X_REQUESTED_WITH}). Then it still doesn't work. Any help is appreciated, Thanks
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");
}
来源:https://stackoverflow.com/questions/39708042/php-detection-of-fetch-api-vs-xmlhttprequest