我有一个名为sample.php的文件,其中包含一些JS代码和一些PHP代码。这是我所拥有的代码的某种样本片段:
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
receiveMessage: function(fxn) {
var callbackFunction = function(event) {
if (typeof fxn === 'function') {
fxn(event.data)
}
};
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
value = message;
});
//sending the value with ajax
$.ajax({
url : "./sample.php", //same file
method : "GET",
data: {"name": value},
success : (res) => {
console.log(value);
},
error : (res) => {
console.log(res);
}
})
</script>
<?php
echo $_GET['name'];
?>
</body>
</html>问题是PHP代码不打印任何东西--有什么错误/bug需要我修复吗?或者有没有更好的方法来访问PHP中的JS变量?
谢谢!:)
发布于 2020-11-03 02:35:01
下面是如何在<script>中访问PHP代码(不使用AJAX):
<?php
echo"<script>";
include ('javascriptStuff.js');
echo'let x = '.json_encode($phpVariable).';';
echo"</script>";
?>https://stackoverflow.com/questions/64649771
复制相似问题