我在我的应用程序中使用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.
参见 developer.mozilla/en-US/docs/Web/API/GlobalFetch/fetch#Parameters 详情。
更多推荐
Fetch Api无法从PHP服务器获取Session
发布评论