我已将 JavaScript 变量传递到 HTML 中的 div id 元素中。我现在尝试将该 div id 发送到 php 变量,以便我可以访问它。
但是,当我尝试 POST 请求时,它没有获取分配给 div id 的内容。感谢任何帮助,谢谢。
<?php
session_start();
$un = $_POST["result"];
echo "the username is". $un;
?>
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
if (typeof(Storage) !== "undefined")
{
var getUser = document.getElementById("result").innerHTML = sessionStorage.getItem("username");
}
else
{
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
最佳答案
首先,要发出发布请求,您需要使用 XMLHttpRequest
。不过,您确实应该在单独的文件中使用 GET
请求。
PHP 文件,名为 getId.php
:
<?php
session_start();
$_SESSION["id"] = $_GET["id"];
?>
JavaScript 代码,用于检索数据:
var getData = function( url, callback ) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr);
};
xhr.open( "get", url, true );
xhr.send();
};
getData('./getId.php?id=' + /* id goes here */, function(json){
if(json.status == 200){
data = json.response;
//Do something with data...
}
})
最后,要引用 session 数据,请返回 HTML 文件:
<?php
session_start();
echo "value of username is: " . $_SESSION["id"];
?>
关于javascript - 将 div id 传递到 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46898078/