2016-11-22 12 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

ボタンがクリックされたときに、ボタンでフォームを行うランダムページへ行くあなたはJavaScriptでこれを行うことができ –

+0

、あなたはそれがなかったすべての – 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ファイルを仮定 http://www.w3schools.com/php/php_forms.asp

<?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.yourserver.com/form-action.php 、PHP_SELFが含まれています:

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

を "/form-action.php" と、あなたはボタンをあなたのポストを扱う

<?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> 
関連する問題