echo Javascript window.location.href 不起作用

echo Javascript window.location.href not working

本文关键字:href 不起作用 location window Javascript echo      更新时间:2023-09-26

我有一个函数,它回显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;
   }
} 

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

回复前面加上Content-Type: text/html' n,并将您的内容包装在 <html></html> 标记中。

试试这种方式。

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

为什么不只使用输出缓冲,而根本不需要处理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();
?>