如何从数据库表中获取行值以在JavaScript / jQuery中使用它?

时间:2018-01-04 07:04:49

标签: javascript php jquery mysql json

我想从数据库中检索行值。 由于我们需要服务器端来访问数据库,我们必须使用PHP来检索值,但我不知道如何在.js文件中使用这个php。

这是我正在尝试但它不起作用。 原因很简单..我们不能在javascript文件中编写PHP。

file.js:

<?php 
$con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
$username = $_SESSION['username'];
$sql = "SELECT * FROM Holders WHERE username='$username'";
$data = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($data);
$address = $row['address'];
?>

$( document ).ready(function() {
    var addressFrmPHP = "<?= $address; ?>";
    var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
});

如何将php $address变量分配给javascript addressFrmPHP变量?

3 个答案:

答案 0 :(得分:3)

您必须创建两个文件,如下所示

  

访问getdata.php

<?php 
$con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
$username = $_SESSION['username'];
$sql = "SELECT * FROM Holders WHERE username='$username'";
$data = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($data);
$address = $row['address'];
echo $address;
?>
  

file.js

$( document ).ready(function() {

    /* AJAX for get data from php page */

    $.post('getdata.php', function(address) {

        var addressFrmPHP = address;
    });

    var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
});

答案 1 :(得分:1)

你必须这样做

<强> test.php的

<?php 
$con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
$username = $_SESSION['username'];
$sql = "SELECT * FROM Holders WHERE username='$username'";
$data = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($data);
$address = $row['address'];

echo '<script> var address= '.$address.';</scrpit>';
?>
<script type='text/javascript' src='js/file.js'></script>

<强> file.js

$( document ).ready(function() {
    var addressFrmPHP = address;
    var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
});

答案 2 :(得分:1)

创建一个文件Getdata.php并编写以下代码:

<?php 
    $con = mysqli_connect($server, $db_user, $db_pwd, $db_name);
    $username = 'nirav4491';
    $sql = "SELECT * FROM Holders WHERE username='$username'";
    $data = mysqli_query($con, $sql);
    $row = mysqli_fetch_assoc($data);
    $address = $row['address'];

?>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="application/javascript">
        $(document).ready(function() {
            var addressFrmPHP = '<?php echo $address; ?>';
            var url = "https://api.examlesite.io/api?module=account&action=bal&add=000000000&address="+addressFrmPHP+"&tag=latest&apikey=APIKEY";
            alert(url);
        });

    </script>
</head>
</html>