[英]Pass div id into PHP variable
I have passed a javascript variable into a div id element in HTML. 我已经将JavaScript变量传递到HTML中的div id元素中。 I am now trying to send that div id to a php variable so I can access it. 我现在正在尝试将该div ID发送到php变量,以便我可以访问它。
However, when I try a POST request it is not grabbing what is assigned to div id. 但是,当我尝试POST请求时,它没有获取分配给div id的内容。 Any help is appreciated, thanks. 任何帮助表示赞赏,谢谢。
<?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>
First of all, to make a post request you'll need to be using XMLHttpRequest
. 首先,要发出发布请求,您将需要使用XMLHttpRequest
。 You really should be using a GET
request in a separate file, though. 不过,您确实应该在单独的文件中使用GET
请求。
PHP file, named getId.php
: PHP文件,名为getId.php
:
<?php
session_start();
$_SESSION["id"] = $_GET["id"];
?>
JavaScript code, to retrieve data: 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...
}
})
And finally, to reference the session data, back in the HTML file: 最后,要引用会话数据,请返回HTML文件:
<?php
session_start();
echo "value of username is: " . $_SESSION["id"];
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.