php - 如何使用 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
一切都正确。
解决方案
对于它的价值,我会给你一个工作的例子。
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
像通常使用的那样使用$_POST
with $.ajax
。
推荐阅读
- asp.net - Microsoft.SqlServer.Types.SqlGeography 反序列化错误
- javascript - 无法在 JavaScript 中从我的 div 中删除数字
- javascript - jQuery 表单验证分配提交按钮
- python - 如何在python中将字符串转换为预定义的变量
- python - 无法在 pyspark 中添加/发送第三方依赖项
- java - 自定义实现 ForEach - Java
- java - java中的int或整数
- node.js - Microsoft 认知服务 API 的原始二进制数据
- android - Android 在 colors.xml 中将颜色淡化 20-30%
- php - 无法在 Symfony 中运行任何进程命令