[英]How can I handle PHP sessions with the Fetch API?
我在 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
做的一切都是正确的。
对于它的价值,我会给你一个工作示例开始。
<!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>
<?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);
您可以像通常将$_POST
与$.ajax
一起使用一样使用$decoded
。
我复制了它,它在 AJAX 上运行良好with
但在fetch
,主体是空白的。 但是,一旦我将.then(res => res.text())
到链中,它就会开始接收正文。 似乎 chrome 正在删除响应正文,而服务器正在正确发送数据。
fetch('/api-url', {
method: 'POST',
body: JSON.stringify({ checked: event.currentTarget.checked }),
mode: "same-origin",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
}
}).then(res => res.text()).then(function(response) {
console.log(response);
});
只需通过处理器管道响应,它就会工作。
您可以使用res.json()
来解析 JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.