单击 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 text 中的字符串仅在我重新加载整个页面时更新。

谢谢 :)

你不能,因为PHP是在服务器端执行的。

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

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

否则您可以像这样手动重新加载页面:

$('#overlay').click(function() {
    // reload the page silently. see also 
    window.location.href = window.location.href;
    //$(this).remove();
});

使用 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>

那么您的其余代码应该可以正常工作。希望这有帮助。

文档: