Fetch Api无法从PHP服务器获取Session [英] Fetch Api unable to get Session from PHP server
问题描述
我在我的应用程序中使用Fetch Api。
I am using Fetch Api in my application.
我有一个PHP服务器页面来获取之前已经定义的会话数据。看起来像这样:
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);
我还有另一个html页面来获取会话数据。看起来像这样:
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>
问题是,当我使用$ .ajax()时,可以正确显示会话数据。但是当我使用fetch()时,会话数据未定义。
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!
推荐答案
如果你想 fetch
发送cookies,你有提供凭证
选项。
If you want fetch
to send cookies, you have to provide the credentials
option.
参见 https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters 详情。
这篇关于Fetch Api无法从PHP服务器获取Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!