在HTML中使用PHP重定向到随机站点

时间:2016-11-22 09:20:25

标签: javascript php html

我需要让用户点击一个按钮,然后重定向到随机页面。

我尝试将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>

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

3 个答案:

答案 0 :(得分:1)

PHP脚本将生成随机URL,当您单击该按钮时,它将调用randsite($url) JavaScript函数,该函数会将您重定向到随机站点。

<?php
    $urls = array("http://www.site1.com", "http://www.site2.com", "http://www.site3.com","http://www.site4.com"); 
    // select random url
    $rand = $urls[mt_rand(0, count($urls) - 1)];
?>

<button onclick="randsite(<?php echo "'".$rand."'"; ?>)">Click</button>

<script type="text/javascript">
function randsite($url){
    window.location = $url;
}
</script>

答案 1 :(得分:1)

试试这个,

<?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>

答案 2 :(得分:0)

PHP + HTML + JS:

 <?php $url = "http://....."; ?>
    <button name="redirect"onclick="redirectFunc(<?php echo $url; ?>);">Redirect with button</button>

    <script>
    function redirectFunc($url){
        window.location.href = "<?php echo $url?>";
    }
    </script>

重定向HTML + PHP: http://www.w3schools.com/php/php_forms.asp

假设您的php文件位于以下地址: http://www.yourserver.com/form-action.php 在这种情况下,PHP_SELF将包含:“/ form-action.php”

<form method="post" action="<?php $_PHP_SELF ?>">
     // type means what should button do submit -> submit your post
     // name how you will recognize which post was sended
     // value value of button which you can get
     <button type="submit" name="redirect" value="redirectValue" id="redirect">Redirect with button post</button>
</form>

然后按钮点击

处理你的帖子
<?php
if(isset($_POST['redirect'])) { 
   // rand your url
   // echo $_POST['redirect']; will output redirectValue
    header('Location: http://....');
}
?>

或使用ahref: http://www.w3schools.com/html/html_links.asp

//or you can use ahref e.g
    <?php $url = "http://..."; 
    // code for randoming url
    ?>

      <a href="<?php echo $url; ?>">Redirect with a href</a></p>

HTML + JS:

<button id="buttonID">redirect</button>

<script type="text/javascript">
    // here you can rand your urls and choose one of them to redirect
    document.getElementById("buttonID").onclick = function () {
        location.href = "http://...";
    };
</script>