在单击PHP / Jquery时更新附加的变量


Update appended variable on click PHP / Jquery

我有一个像这样的数组

     <?php 
        $info = array(
            "cat",
            "dog",
            "bear"
            );
    ?>

我在叠加层上随机输出一个字符串,例如

<script>
var text = '<?php echo $info[array_rand ($info)];?>';
$(function() {
var loading = function() {
    var over = '<div id="overlay">' + '<p class="info">' + text + '</p>' + '</div>';         
    $(over).appendTo('body');
    $('#overlay').click(function() {
        $(this).remove();
    });

    $(document).keyup(function(e) {
        if (e.which === 27) {
            $('#overlay').remove();
        }
    });
};
$('.wrapper').click(loading);
});
</script>

.CSS:

#overlay {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #000;
opacity: 0.90;
height: 200%;
}
.info{
position: absolute;
width: 100%;
top: 25%;
height: 200px;
font-size: 50px;
color: white;
text-align: center;
}

我的问题是:如何通过单击正文更新 var 文本并在每次打开叠加层时获取新的随机字符串?到目前为止,var 文本中的字符串仅在我重新加载整个页面时更新。

感谢:)

使用 JSON 在页面中打印 PHP 数组:

<!-- language: lang-php -->
<?php
$info = array(
            "cat",
            "dog",
            "bear"
            );
?>
<!-- language: lang-js -->
<script type="text/javascript">
// (it's better to retrieve it in ajax)
var arr = <?php echo json_encode($info); ?>;
//  2. Roll some dice in Javascript
// Math.random returns a random value between 0 and 1
var text = "";
// wrapped in a function so you can pick new random values
function pickRandom() {
    // Math.random returns a decimal number, and you need to access arrays using their indexes (0, 1, 2) not decimal numbers. Number.parseInt does the rounding.
    text = arr[ Number.parseInt( Math.random()*arr.length ) ];
    alert("new random value is: " + text);
}
pickRandom();
</script>

然后,代码的其余部分应该可以工作。希望这有帮助。

医生:

  • JSON 编码:http://php.net/manual/fr/function.json-encode.php
  • JS随机性:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
你不能,

因为PHP是在服务器端执行的。

当您加载页面时,它会将最终的 HTML 发送到您的浏览器,结果为 <?php echo $info[array_rand ($info)];?> .

如果安全性不是问题(游戏,银行业务...),您可以使用JavaScript使用随机性。

否则,您可以手动重新加载页面,如下所示:

$('#overlay').click(function() {
    // reload the page silently. see also http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
    window.location.href = window.location.href;
    //$(this).remove();
});