如何通过 PHP 连接 javascript 和 MySQL? [英] How do I connect javascript and MySQL via PHP?

查看:40
本文介绍了如何通过 PHP 连接 javascript 和 MySQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的网络应用程序.我有一个存储值的 MySQL 数据库.当我加载我的网站时,我想运行一个 php 脚本,该脚本从数据库中检索所述值并将其传递给 javascript.然后我使用 javascript 来禁用或不禁用按钮.

I am developing a simple web application. I have a MySQL database which stores a value. When I load my website, I want to run a php script that retrieves said value from the DB and passes it to javascript. I then use the javascript to either disable a button or not.

在我的 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 脚本中获取结果.

How can I tell my javascript in the index.html which php script to use (I have multiple)? So when the website loads I want my javascript to get the result from the getValueFromDB.php script.

非常感谢!

推荐答案

尝试使用 <?php include 'filepath' ;?> 包括阅读文档这里,我认为是你需要什么

Try using the <?php include 'filepath' ; ?> includes reading documentation here, I think that is what you need

<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,反之亦然.

You can not tell javascript how to use PHP, because JS is a client language and a PHP server language and the workflow is first PHP and second JS and not vice versa.

如果需要用JS取php数据,需要使用AJAX

If you need to take php data with JS, you need to use AJAX

好吧(这是一个例子,未经测试)

well (it's an example, not tested)

<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 和 MySQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆