我正在使用PHP,我在一个页面中有一个名为"row"的Javascript对象,其中包含一些数据,我知道如何使用localStorage
将其传递到另一个页面,但我想知道我可以在第二页中使用PHP函数读取这个JS对象吗?
您可以将对象存储在 cookie 而不是 localStorage 中。
Cookie 只能存储字符串,所以你应该用 javascript JSON.stringify
将你的对象编码为字符串,然后使用 json_decode
在 PHP 中解码它。
请参阅此处如何使用 javascript 设置 cookie。
下面是一个示例:
var data = {/*your data*/},
string_data = JSON.stringify( data );
setCookie( 'my_data', string_data );
然后在 PHP 中:
$data = json_decode( $_COOKIE[ 'my_data' ] );
您可以使用:
json_decode(string $json)
请参阅 http://php.net/manual/en/function.json-decode.php 中的文档这将采用 JSON 编码的字符串并将其转换为 PHP 变量。
你到底想做什么?
PHP 本身无法读取 js 对象或变量,但您可以通过 ajax 的 post/get 请求将它们传递给 php(例如)。
要将 js 对象传递给 php,请使用 json。
在 js 中:
JSON.stringify(j);
在 PHP 中:
json_decode(json);
使用 JavaScript
设置localStorage
或sessionStorage
并使用 JavaScript 检索值,没有服务器代码可以直接访问它。
页1:
if(typeof(Storage) !== "undefined") {
localStorage.setItem("YourKey", "Your Value");
//replace "Your Value" with 'row' object
} else {
console.log("No Web Storage support..");
}
if(typeof(Storage) !== "undefined") {
sessionStorage.setItem("YourKey", "Your Value");
//replace "Your Value" with 'row' object
} else {
console.log("No Web Storage support..");
}
页2:
if(typeof(Storage) !== "undefined") {
localStorage.getItem("YourKey");
} else {
console.log("No Web Storage support..");
}
if(typeof(Storage) !== "undefined") {
sessionStorage.getItem("YourKey");
} else {
console.log("No Web Storage support..");
}
使用JSON.stringify()
字符串化row
对象,并通过查询字符串或 cookie 或表单发布将值发送到 PHP。