在Javascript中包含已定义的PHP变量

时间:2022-01-10 08:06:51

I am not too familiar with Javascript so I was hoping I could get a little advice on how to include a PHP variable within javascript.

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

I have written a PHP code to set a variable waiting time for a hyperlink depending on server load.

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

A snippet of the PHP code is:

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";
}

I am trying to echo $wait_level within the Javascript. I have done it the HTML method below, but obviously this isn't correct. Can anybody suggest a functional approach?

我试图在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>

I am aware the javascript I am using will allow you to easily view the hyperlink by viewing the source, but this isn't the final javascript code I will be using so there is no need to worry about that.

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

The script will only be used for 1 day on a private server so does not need to be clean, just functional.

该脚本仅在私人服务器上使用1天,因此不需要干净,只需要功能。

Any help is really very much appreciated!

任何帮助真的非常感谢!

3 个解决方案

#1


1  

The way I'd go about getting PHP to JavaScript would be using Ajax

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

Ajax you'll be able to load data from your server by using a HTTP Post request, the good thing about using Ajax is that you can send parameters with the HTTP request. E.g. If you wanted to send a parameter which would be used for a DB query. Then you'd be able to do so and you'd be able to return the data from that DB query.

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

I'm not saying it's bad practise to use PHP inside JavaScript because it's perfectly acceptable, but it can be very risky - you're generating parts of the JS on-the-fly, which means you have to generate VALID JS code, or the whole code block will be killed by a syntax error.

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

e.g.

例如

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

and $lastName happens to be O'Neil, you've now introduced a syntax error, because the generated code will be:

而$ 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 ';'

So if you was going to carry on with inserting raw PHP-based data into a JS variable, you basically MUST use json_encode(), which guarantees that the generated JS data is syntactically valid JS code

因此,如果您要继续将基于PHP的原始数据插入到JS变量中,您基本上必须使用json_encode(),这可以保证生成的JS数据在语法上是有效的JS代码

My method getting PHP data

获取PHP数据的方法

Server side - Test1.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 Side - Test.php

HTML Side - 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>

#2


0  

I am not sure if there is a better way of doing it, but I have managed to make it work with the following code:

我不确定是否有更好的方法,但我已设法使用以下代码:

<html>
<head>

<div id="dom-target" style="visibility: hidden">
<?php 
    echo htmlspecialchars($wait_level); 
?>
</div>

<script type="text/javascript">
var div = document.getElementById("dom-target");
var myData = div.textContent;
window.onload=function() {
document.getElementById('redirect').style.display = 'none';
function countdown() {
if ( typeof countdown.counter == 'undefined' ) {
   countdown.counter = myData; // 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>

#3


-1  

You can create parameterized functions in javascript like this

你可以在这样的javascript中创建参数化函数

 function countdown(counter) {
    if ( counter != 'undefined' and counter != -1  ) 
    {
       if(counter >= 0) {
        document.getElementById('count').innerHTML = counter--;
        setTimeout(countdown(counter), 500);
       }
    else {
       document.getElementById('redirect').style.display = '';
       }
    }
}
    countdown(<?php echo $wait_level ?>);

#1


1  

The way I'd go about getting PHP to JavaScript would be using Ajax

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

Ajax you'll be able to load data from your server by using a HTTP Post request, the good thing about using Ajax is that you can send parameters with the HTTP request. E.g. If you wanted to send a parameter which would be used for a DB query. Then you'd be able to do so and you'd be able to return the data from that DB query.

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

I'm not saying it's bad practise to use PHP inside JavaScript because it's perfectly acceptable, but it can be very risky - you're generating parts of the JS on-the-fly, which means you have to generate VALID JS code, or the whole code block will be killed by a syntax error.

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

e.g.

例如

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

and $lastName happens to be O'Neil, you've now introduced a syntax error, because the generated code will be:

而$ 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 ';'

So if you was going to carry on with inserting raw PHP-based data into a JS variable, you basically MUST use json_encode(), which guarantees that the generated JS data is syntactically valid JS code

因此,如果您要继续将基于PHP的原始数据插入到JS变量中,您基本上必须使用json_encode(),这可以保证生成的JS数据在语法上是有效的JS代码

My method getting PHP data

获取PHP数据的方法

Server side - Test1.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 Side - Test.php

HTML Side - 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>

#2


0  

I am not sure if there is a better way of doing it, but I have managed to make it work with the following code:

我不确定是否有更好的方法,但我已设法使用以下代码:

<html>
<head>

<div id="dom-target" style="visibility: hidden">
<?php 
    echo htmlspecialchars($wait_level); 
?>
</div>

<script type="text/javascript">
var div = document.getElementById("dom-target");
var myData = div.textContent;
window.onload=function() {
document.getElementById('redirect').style.display = 'none';
function countdown() {
if ( typeof countdown.counter == 'undefined' ) {
   countdown.counter = myData; // 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>

#3


-1  

You can create parameterized functions in javascript like this

你可以在这样的javascript中创建参数化函数

 function countdown(counter) {
    if ( counter != 'undefined' and counter != -1  ) 
    {
       if(counter >= 0) {
        document.getElementById('count').innerHTML = counter--;
        setTimeout(countdown(counter), 500);
       }
    else {
       document.getElementById('redirect').style.display = '';
       }
    }
}
    countdown(<?php echo $wait_level ?>);