在php上使用变量在JS中创建另一个变量

时间:2018-11-23 05:29:46

标签: javascript php jquery database

我很难在php中获取要在js中使用的特定变量的值。这是我在php中的代码:

<?php
require("connection.php");

$sql_cmd = "SELECT * FROM tbstatus";

$stmt = $con->prepare($sql_cmd);
$stmt->execute();

echo "<h2>STATUS OF THE BABY</h2>";

while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<h4>" . $result['status'] . "</h4>";
}
?>

我想获取此值($ result ['status'])并将其传递给js中的变量pos。这是我的js代码:

setInterval(function() {
    $("#position").load('refresh.php');
    notif();

}, 1000);

function notif() {
    var pos = $('PHP VARIABLE HERE').val();
    alert(pos);
}

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

最简单的方法是将其直接输出到javascript:

?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...

window.MY_PHP_VAR now contains your php variable

答案 1 :(得分:1)

如果您的JavaScript代码位于要显示结果的同一页上,那么您可以使用此

var pos =  `<?php echo $result['status'] ?>`;

var pos =  `<?= $result['status'] ?>`;

答案 2 :(得分:-1)

  1. 您可以尝试为状态指定ID或类别。
  2. 然后在JavaScript中可以获取id或类的值。

PHP

<?php
require("connection.php");

$sql_cmd = "SELECT * FROM tbstatus";

$stmt = $con->prepare($sql_cmd);
$stmt->execute();

echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}

?>

JavaScript

var oldStatus = '';

setInterval(function() {
    $("#position").load('refresh.php');
    notif();
}, 1000);

function notif() {
    // note that since we used a class, you will get the value of the first element only.
    var pos = $('.status').text(); // use .text() instead of .val()
    if (pos.toLowerCase() == 'out' && pos != oldStatus){
        oldStatus = pos;
        alert(pos);
    }
}

答案 3 :(得分:-1)

===============
// refresh.php
===============

<?php  
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();

echo "<h2>STATUS OF THE BABY</h2>";

while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo "<h4>" . $result['status'] . "</h4>";
      echo "<script> alert('". $result['status'] ."'); </script>";
      /* If the $result['status'] is 'success' the above line will be converted to:
       echo "<script> alert('success'); </script>";
      */
}

?>

因此,每次refresh.php加载时,脚本都将执行。

但是,我建议您为h4分配一个id或class属性,以在其中回显状态并使用javascript中的选择器访问该值。