I am using Fetch Api in my application.
I have a PHP server page to retrieve session data that has already been defined previously. It looks 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 session data. It looks 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 that when I use $ .ajax (), the session data can be displayed correctly. But when I use fetch (), the session data was undefined.
So what is wrong and how can I fix it? Thanks!
ogoss source share