I am using Fetch Api in my application.
I've got a PHP server page to get session data which was already defined before. It seemd like this:
<?php
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
session_start();
// $_SESSION['data'] already defined before
$result = array();
// print_r($_SESSION['data']);
if (isset($_SESSION['data'])) {
$result = $_SESSION['data'];
$result['code'] = 'ok';
} else {
$result['code'] = 'error';
}
echo json_encode($result, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
I also got another html page to get the session data. It seemd like this:
<script>
$(function() {
// use $.ajax
$.ajax({
url: 'session.php',
dataType: 'json'
})
.done(function(res) {
console.log(res);
});
// end
// use fetch
fetch('session.php').then(function(res) {
if (res.ok) {
res.json().then(function(obj) {
console.log(obj);
});
}
});
// end
});
</script>
The problem is, when I use $.ajax(), session data can be correctly showed. But when I use fetch(), the session data was undefined.
So, what goes wrong and how can I fix it? Thanks!
If you want fetch to send cookies, you have to provide the credentials option.
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters for details.
jquery ajax is a usual ajax request and the browser is sending the cookie header with the session id that identify your session.
fetch doesnt - instead a new session is created with out any data send the php session id either with url or header
have a look at: http://php.net/manual/en/session.idpassing.php
来源:https://stackoverflow.com/questions/36741581/fetch-api-unable-to-get-session-from-php-server