首页 > 解决方案 > 如何使用 Fetch API 处理 PHP 会话?

问题描述

我在我的 JavaScript 中使用 Fetch API:

fetch('/api-url', {
    method: 'POST',
    body: JSON.stringify({ checked: event.currentTarget.checked }),
    mode: "same-origin",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json"
    }
}).then(function(response) {
    console.log(response);
});

哪个发布到 PHP 后端。但是,当我打电话时session_start,脚本会爆炸。没有错误消息,即使所有错误日志都打开并且我的错误处理程序被禁用。

<?php
session_start();
echo('Hello, world!');
die;

它适用于常规浏览器请求。我正在使用 PHP 7.2.9。我可以看到请求中传递了会话 ID,所以看起来Fetch一切都正确。

标签: php

解决方案


对于它的价值,我会给你一个工作的例子。

fetch-to.html(或 *.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <script>

        const data = { username: 'example' };

        fetch('fetch-from.php', {
            method: 'POST', // or 'PUT'
        mode: "same-origin",
        credentials: "same-origin",
            headers: {
                'Content-Type': 'application/json',  // sent request (alt: 'application/x-www-form-urlencoded')
                'Accept':       'application/json'   // expected data sent back
            },
            body: JSON.stringify(data),
        })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });

    </script>

</body>
</html>

fetch-from.php

<?php

$contentType = isset($_SERVER["CONTENT_TYPE"])
    ? trim($_SERVER["CONTENT_TYPE"])
    : '';

if ($contentType !== "application/json") {

    $response = [
        'data'      => '',
        'errorCode' => '1',
        'errorText' => 'Incorrect contentType. Should be "application/json".'
    ];

} else {

  // Receive the RAW post data.
  $content = trim(file_get_contents("php://input"));

    // Decode data
  $decoded = json_decode($content, true);

  if (!is_array($decoded)) {
        // If json_decode failed, the JSON is invalid.
        $response = [
            'data'      => '',
            'errorCode' => '2',
            'errorText' => 'JSON invalid. Could not decode.'
        ];
  } else {
        // Do your magic
        $response = [
            'data'      => [
                'empty' => 'true',
            ],
            'errorCode' => '0',
            'errorText' => ''
        ];

        // For you example
        session_start();
        $response['data'] = $_SESSION;
  }
}

echo json_encode($response);

您可以$decoded像通常使用的那样使用$_POSTwith $.ajax


推荐阅读