[英]How do I connect javascript and MySQL via PHP?
我正在开发一个简单的Web应用程序。 我有一个存储值的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脚本中获取结果。
非常感谢!
您可以在页面加载时使用Ajax尝试
$( document ).ready(function() {
$.ajax({
url: "yourphpfile.php",
success: function(response){
if(result == 0)
{
document.getElementsByName("button1")[0].disabled = true; // instead of this maybe its better to use jquery - example below
$('#button1').prop( "disabled", true );
}
}
});
});
尝试使用<?php include 'filepath' ; ?>
<?php include 'filepath' ; ?>
包括阅读文档这里 ,我认为这是你需要什么
<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
?>
通常,您将使您的php脚本回显您想要获取的值,并从javascript执行ajax调用以获取值,因此
PHP:
<?php
<!-- retrieve value from DB here (This part is not the problem)-->
$someVar = 0;
echo $someVar;
?>
和js(如果需要,可以将其直接放在html中)。
<script>
var dbData;
var ajax = new XMLHttpRequest();
ajax.open("GET", "PATH_TO_PHP_SCRIPT/getValueFromDB.php", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
dbData=data;
//Deal with the response
}
</script>
或者,使用jQuery:
<script>
var dbData;
$.ajax({
url: "PATH_TO_YOUR_PHP_SCRIPT/getValueFromDB.php",
method: "GET"
}).done(function(d) {
dbData=d;
//Deal with the response
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.