Fetch Api unable to get Session from PHP server

≯℡__Kan透↙ 提交于 2019-12-01 16:33:55

问题


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!


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!