在HTML中使用PHP重定向到一个随机网站

问题描述:

我需要能够让用户点击一个按钮,并被重定向到一个随机页面。在HTML中使用PHP重定向到一个随机网站

我试图把JavaScript代码里面的PHP和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> 

我知道这可能有很多错误,并帮助是非常赞赏。谢谢!

+0

做一个按钮,然后当按钮被点击进入随机页面 –

+0

你可以在Javascript中做一个表格,你根本就不 – Vuldo

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> 

试试这个,

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

它并不需要的PHP工作,但谢谢! –

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>