Fetch Api无法从PHP服务器获取Session

编程入门 行业动态 更新时间:2024-10-21 05:57:58
本文介绍了Fetch Api无法从PHP服务器获取Session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在我的应用程序中使用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

本文发布于:2023-11-26 18:20:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器   Api   Fetch   Session   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!