javascript - 在 Javascript 中包含定义的 PHP 变量

标签 javascript php html

我对 Javascript 不太熟悉,所以我希望能得到一些关于如何在 javascript 中包含 PHP 变量的建议。

我编写了一段 PHP 代码来根据服务器负载设置超链接的可变等待时间。

PHP 代码片段是:

// set wait level
if($count_user_online <= "99") {
    $wait_level="0";
}
else if($count_user_online >= "100" && $count_user_online < "199") {
    $wait_level="60";
}
else if($count_user_online >= "200" && $count_user_online < "299") {
    $wait_level="120";
}
else if($count_user_online >= "300" && $count_user_online < "399") {
    $wait_level="180";
}
else if($count_user_online >= "400" && $count_user_online < "499") {
    $wait_level="240";
}
else if($count_user_online >= "500") {
    $wait_level="300";
}

我试图在 Javascript 中回显 $wait_level 。我已经用下面的 HTML 方法完成了它,但显然这是不正确的。有人可以建议一种功能性方法吗?

<html>
<head>
<script type="text/javascript">
window.onload=function() {
document.getElementById('redirect').style.display = 'none';
function countdown() {
if ( typeof countdown.counter == 'undefined' ) {
   countdown.counter = <?php echo $wait_level ?>; // seconds
   }
if(countdown.counter >= 0) {
   document.getElementById('count').innerHTML = countdown.counter--;
   setTimeout(countdown, 1000);
   }
else {
   document.getElementById('redirect').style.display = '';
   }
}
countdown();
};
</script>

</head>
<body>
<h2>You can can access the link in <span id="count"></span> seconds <a id="redirect" href="http://google.com/">Google</a></h2>
</body>
</html>

我知道我使用的 JavaScript 允许您通过查看源代码轻松查看超链接,但这不是我将使用的最终 JavaScript 代码,因此无需担心这一点。

该脚本仅在私有(private)服务器上使用 1 天,因此不需要干净,只需功能即可。

非常感谢任何帮助!

最佳答案

我将 PHP 转换为 JavaScript 的方法是使用 Ajax

Ajax 您将能够使用 HTTP Post 请求从服务器加载数据,使用 Ajax 的好处是您可以通过 HTTP 请求发送参数。例如。如果您想发送用于数据库查询的参数。然后您就可以这样做,并且可以从该数据库查询返回数据。

我并不是说在 JavaScript 中使用 PHP 是不好的做法,因为它是完全可以接受的,但它可能非常危险 - 你正在动态生成 JS 的一部分,这意味着你必须生成有效的 JS代码,否则整个代码块将被语法错误杀死。

例如

<script type="text/javascript">
   var lastName = '<?php echo $lastName ?>';
</script>

并且 $lastName 恰好是 O'Neil,您现在引入了语法错误,因为生成的代码将是:

var lastName = 'O'Neil';
                --- string with contents O
                   --- unknown/undefined variable Neil
                     -- string followed by variable, but no operator present.
                        --- start of a new unterminated string containing a ';'

因此,如果您打算继续将基于 PHP 的原始数据插入 JS 变量,则基本上必须使用 json_encode(),它保证生成的 JS 数据是语法上有效的 JS 代码

我获取PHP数据的方法

服务器端 - Test1.php

<?php

if (isset($_POST['usersOnline']))
{


$count_user_online = $_POST['usersOnline'];

switch ($count_user_online) {
    case  ($count_user_online <= "99"):
            $wait_level = "0";
        break;

    case  ($count_user_online >= "100" && $count_user_online < "199"):
            $wait_level = "1";
        break;

    case  ($count_user_online >= "200" && $count_user_online < "299"):
            $wait_level = "2";
        break;
}

echo $wait_level;

}

?>

HTML 端 - Test.php

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">     </script>
<script>

$(document).ready(function() {
    sendUserCount("200");
    document.getElementById('redirect').style.display = 'none';
});

function countdown(count) {
     if ( typeof countdown.counter == 'undefined' ) {
        countdown.counter = count; // seconds
     }

     if(countdown.counter >= 0) {
        document.getElementById('count').innerHTML = countdown.counter--;
        setTimeout(countdown, 1000);
     }
     else {
        document.getElementById('redirect').style.display = '';
     }
  }

  function sendUserCount(userCount)
  {
     var url = document.location.href;
     $.post("test1.php",
     {
        usersOnline: userCount
     })

     .success(function (data)
     {
        console.log(data);
        countdown(data);
     });
   }

</script>

</head>
<body>
  <h2>You can can access the link in <span id="count"></span> seconds <a id="redirect" href="http://google.com/">Google</a></h2>
</body>
</html>

关于javascript - 在 Javascript 中包含定义的 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30802057/

相关文章:

php - WordPress - 将第一张图片设为我的特色图片

asp.net - 我如何在不使用表格的情况下在 CSS 中执行此操作?

css - 如何使导航栏永久位于顶部?

javascript - 在所有浏览器中悬停时动画 svg 路径

javascript - react Hook : Set state 'ModalVisible' but state does not update immediately

javascript - Chart.js v2 - 隐藏网格线

php - 跨域发布,无需访问服务器

javascript - 如何将 Twitter 关注按钮放置在图像顶部

php - PHP最佳星级评定解决方案

javascript - 谷歌地图教程无法使用