如何使用php中的onclick事件重定向页面?

时间:2013-12-25 06:10:46

标签: php html

我尝试使用此代码,但它无效,

<input type="button" value="Home" class="homebutton" id="btnHome" onClick="<?php header("Location: /index.php"); ?>" />

4 个答案:

答案 0 :(得分:13)

你不能使用php代码客户端。你需要使用javascript。

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="document.location.href='some/page'" />

但是,你真的不应该使用内联js(比如onclick here)。在此研究:https://www.google.com/search?q=Why+is+inline+js+bad%3F

以下是一种干净的方法: Live demo (click).

<强>标记:

<button id="myBtn">Redirect</button>

<强> JavaScript的:

var btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
  document.location.href = 'some/page';
});

如果你需要用php编写位置:

  <button id="myBtn">Redirect</button>
  <script>
    var btn = document.getElementById('myBtn');
    btn.addEventListener('click', function() {
      document.location.href = '<?php echo $page; ?>';
    });
  </script>

答案 1 :(得分:1)

为什么人们一直在混淆php和javascript?

PHP SERVER SIDE
JAVASCRIPT(如onclick)是 CLIENT SIDE

您必须使用只是 javascript来重定向。否则,如果您想要涉及PHP,您可以使用AJAX调用来记录命中或任何您想要发回的URL或其他详细信息。

答案 2 :(得分:1)

您使用的是onclick这是javascript事件。 有两种方式

的Javascript

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="window.location = 'http://google.com'" />

或PHP

创建另一个页面为redirect.php并放入

<?php header('location : google.com') ?>

并在同一目录中的任何页面上插入此链接

<a href="redirect.php">google<a/>

希望这有助于它最简单!!

答案 3 :(得分:0)

请试试这个

    <input type="button" value="Home" class="homebutton" id="btnHome" onClick="Javascript:window.location.href = 'http://www.website.com/index.php';" />

window.location.href示例:

 window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open()示例:

     window.open('http://www.google.com'); //This will open Google in a new window.