echo Javascript window.location.href 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10112047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:53:11  来源:igfitidea点击:

echo Javascript window.location.href not working

phpjavascriptnavigationecho

提问by zed

I have a function which echoes javascript to navigate to a different page. While navigation occurs, the

我有一个函数可以回显 javascript 以导航到不同的页面。当导航发生时,

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

does not work and simply prints it on the screen.

不起作用,只是将其打印在屏幕上。

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

I use my function this way: redirect("./index.php");

我这样使用我的功能: redirect("./index.php");

My php function is as follows

我的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;
   }
} 

采纳答案by Peter Aron Zentai

Your browser treats the response as plaintext.

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

Prepend to you response a Content-Type: text/html\n plus wrap your content inside an <html></html>tag.

预先为您响应Content-Type: text/html\n 加上将您的内容包装在<html></html>标签中。

回答by Shankar Damodaran

Try this way.

试试这个方法。

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

回答by John Conde

Why not just use output bufferingand not have to deal with JavaScript or meta redirects at all?

为什么不直接使用输出缓冲而不用处理 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();
?>