我有一个 php 文件 content.php,当前正在浏览器中加载:
<html>
<head>
<title>Content</title>
<script src="content.js"></script>
</head>
<body>
<?php
if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
?>
Content for users with status 1
<?php
} else {
?>
Content for users with different status
<?php
}
?>
</body>
</html>
我想做的是设置
$_POST["status"]
内部变量
content.js
我考虑过使用隐藏的 html 表单并通过 javascript 单击提交按钮,但这看起来并不是一个优雅的解决方案。
我也考虑过使用 XMLHttpRequest,问题是我还没有找到通过 XMLHttpRequest 将数据发送到当前查看/加载页面的方法。
我没有使用额外的库,只有 javascript 和 php。
对于隐藏的 html 表单,是否有更优雅的解决方案?
最佳答案
似乎您需要使用 AJAX,因为您需要以隐藏方式执行服务器端脚本并更新 html。
interface.php
有content.js
和一个div
content.js
发送带有status
的ajax post请求content.php
根据status
发送内容
interface.php
的div
已更新。
这里是 content.js
和 interface.php
let status = 1;
loadDoc(status);
function loadDoc(status) {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML =
xhttp.responseText;
}
};
xhttp.open("POST", "content.php", true);
xhttp.send("status=" + status);
}
<html>
<head>
<title>Content</title>
<script src="content.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
这是你的content.php
<?php
if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
?>
Content for users with status 1
<?php
} else {
?>
Content for users with different status
<?php
}
?>
宾果游戏!您通过 content.js
$_POST["status"]
关于javascript - 从js脚本发送数据到当前的php文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880206/