我正在开发一个简单的网络应用程序。我有一个存储值的 MySQL 数据库。当我加载我的网站时,我想运行一个 php 脚本,该脚本从数据库中检索所述值并将其传递给 javascript。然后我使用 javascript 来禁用或不禁用按钮。
在我的 index.html 中:
<form action="someOtherScript.php" method="get">
<input type="submit" name="button1" value="Run me now!">
</form>
<script>
var value = "<?php echo $someVar; ?>";
if(value == 0){
document.getElementsByName("button1")[0].disabled = true;
}
</script>
在我的 getValueFromDB.php 中:
<?php
<!-- retrieve value from DB here (This part is not the problem)-->
$someVar = 0;
?>
如何在 index.html 中告诉我的 javascript 使用哪个 php 脚本(我有多个)?因此,当网站加载时,我希望我的 javascript 从 getValueFromDB.php 脚本中获取结果。
非常感谢!
最佳答案
尝试使用 <?php include 'filepath' ; ?>
包括阅读文档 here , 我想这就是你需要的
<form action="someOtherScript.php" method="get">
<input type="submit" name="button1" value="Run me now!">
</form>
<script>
<?php include 'getValueFromDB.php' ; ?>
var value = "<?php echo $someVar; ?>";
if(value == 0){
document.getElementsByName("button1")[0].disabled = true;
}
</script>
你不能告诉 javascript 如何使用 PHP,因为 JS 是一种客户端语言,也是一种 PHP 服务器语言,工作流首先是 PHP,其次是 JS,而不是相反。
如果需要用JS取php数据,需要用AJAX
好吧(这是一个例子,没有测试过)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="someOtherScript.php" method="get">
<input type="submit" name="button1" value="Run me now!">
</form>
<script>
$.ajax({
url: "getValueFromDB.php",
success: function(result){
if(result == 0){
document.getElementsByName("button1")[0].disabled = true;
}
}});
</script>
PHP
<?php
<!-- retrieve value from DB here (This part is not the problem)-->
$someVar = 0;
echo $someVar
?>
关于javascript - 如何通过 PHP 连接 javascript 和 MySQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49674187/