echo Javascript window.location.href无效

zed*_*zed 6 javascript php navigation echo

我有一个函数,它回应javascript导航到另一个页面.导航发生时,

echo 'window.location.href="'.$url.'";'; 
Run Code Online (Sandbox Code Playgroud)

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

"window.location.href="./index.php";
Run Code Online (Sandbox Code Playgroud)

我用这种方式使用我的函数: 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;
   }
} 
Run Code Online (Sandbox Code Playgroud)

Pet*_*tai 4

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

在您的响应前面添加Content-Type: text/html\n 并将您的内容包装在<html></html>标签内。