echo Javascript window.location.href无效

时间:2012-04-11 18:46:21

标签: php javascript navigation echo

我有一个回复javascript导航到不同页面的功能。在导航发生时,

echo 'window.location.href="'.$url.'";'; 

不起作用,只需将其打印在屏幕上即可。

"window.location.href="./index.php";

我以这种方式使用我的功能:redirect("./index.php");

我的php功能如下

  function redirect($url)
   {    
    if (!headers_sent())
    {    
      header('Location: '.$url);
      exit;
    }
   else
    {      
      echo '<script type="text/javascript">';
      echo 'window.location.href="'.$url.'";';
      echo '</script>';
      echo '<noscript>';
      echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
      echo '</noscript>'; exit;
   }
} 

3 个答案:

答案 0 :(得分:4)

您的浏览器将响应视为纯文本。

预先向您回复Content-Type: text/html\ n并将您的内容包装在<html></html>标记内。

答案 1 :(得分:1)

为什么不使用output buffering而不必处理JavaScript或元重定向?

<?php
// Top of your page
ob_start();

// Code goes here

// Redirect
if ($redirect_is_necessary)
{
    header('Location: '.$url);
    exit;
}

// Rest of page goes here

// Bottom of page
ob_end_flush();
?>

答案 2 :(得分:0)

试试这种方式。

<?php
$yourURL="http://www.stackoverflow.com";
echo ("<script>location.href='$yourURL'</script>");
?>