This question already has an answer here:
How Can I Create a Button that links to multiple websites randomly?
                            
                                (1个答案)
                            
                    
                3年前关闭。
        

    

我需要能够让用户单击一个按钮,然后将其重定向到随机页面。

我尝试将PHP放入JavaScript内,然后将其放入HTML内,如下所示:

<script>
<button onclick="var jsVar = "<?php
$urls = array("www.site1.com", "www.site2.com", "www.site3.com","www.site4.com");
$url = $urls[array_rand($urls)];
header("Location: http://$url"); ?>"">Click</button>
</script>


我知道这可能有很多错误,非常感谢您的帮助。谢谢!

最佳答案

尝试这个,

<?php
$urls = array("www.site1.com", "www.site2.com", "www.site3.com","www.site4.com");
$url = $urls[array_rand($urls)];
?>
<button onclick="myfunction();">Click</button>
<script>
function myfunction(){
    var href = "<?php echo $url?>";
    window.location.href = "http://"+href;
}
</script>

08-18 02:03