2016-11-22 34 views
0

我需要能夠讓用戶點擊一個按鈕,並被重定向到一個隨機頁面。在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

回答

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

試試這個,

<?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工作,但謝謝! –

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>