通过 JS 发送 Cookie 到 PHP

Send Cookie via JS to PHP

我正在尝试将 Javascript 内的字符串发送到我的服务器。我让它创建了一个 cookie,现在我想让它做一些事情(现在:一个简单的回声)。这是我的按钮功能(我正在使用 Bokeh):

const d = s.data;
var clustOut = "Nevermind the real input";




if (numberOfColors.length >= 2) {
  localStorage.setItem("input", clustOut);
  
 document.cookie = ('clustOut=' + clustOut + ';max-age=10368000;' + ';path=/');
 window.location.href = "/php-scripts/post_cluster.php";
 //alert(numberOfColors.length  + "\n" + clustOut);
 //alert(d["x"] +  d["y"] + d["color"]);


} else {
 alert ("You have to assign the points to at least two clusters!");
}

我的PHP-文件应该简单地回显:

<?php
$clustOut = $_COOKIE['clustOut'];

echo $clustOut;
?>

我很确定 window.location.href = "/php-scripts/post_cluster.php"; 可能是错误的提交命令。我该怎么做才能让我的 PHP-Script 获得我刚刚设置的 Cookie?

使用 Fetch 发送数据 API。

客户端和服务器之间可以通过HTTP协议进行通信。每当您加载网页时,都会向服务器发送 HTTP 请求,并将响应发送回客户端。您可以发出自己的请求并通过与 Fetch API.

相同的协议与服务器通信

您将数据发送到服务器并等待响应返回。通过这种方式,您可以检查服务器收到的内容,并可能对您返回的响应进行处理。

let data = {
  clustOut: "Nevermind the real input"
};

fetch('/php-scripts/post_cluster.php', {
  method: 'POST',
  body: JSON.stringify(data)
}).then(response => {
  if (response.status === 200 && response.ok) {
    return response.text();
  }
}).then(message => {
  console.log(message);
});

使用 XMLHttpRequest (IE10+) 发送数据

对于不支持 Fetch API 的浏览器,回退到较旧的 XMLHttpRequest。它做同样的事情,但写法不同。

var xhr = new XMLHttpRequest();
xhr.onload = function() {
  if (this.status === 200) {
    console.log(this.responseText);
  }
}
xhr.open('POST', '/php-scripts/post_cluster.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(JSON.stringify(data));

使用表单发送数据。

一种更类似的方法是使用 <form> 元素,其中 action 属性指向您的 PHP 脚本。这也会在重新加载页面时向 PHP 文件发送请求。但是,读出响应的工作方式不同,因为您需要在呈现期间在页面上显示响应以查看结果。

<form method="POST" action="/php-scripts/post_cluster.php"> 
  <input type="hidden" name="clustOut" value="Nevermind the real input">
  <button type="submit">Send</button>
</form>

正在服务器上接收数据

因为在上面的示例中我们使用了 POST 方法来发送数据,所以我们需要访问 PHP 中的全局 $_POST 变量来读取已发送的数据。返回或回显的值将在对客户端的响应中发回。

<?php

$clust_out = isset( $_POST[ 'clustOut' ] ) ? $_POST[ 'clustOut' ] : '';
return $clust_out . ' has been received';

?>