简体   繁体   English

为什么heder('Location:index')不起作用,但是window.location.href ='index.php'起作用?

[英]Why heder('Location:index')not working but window.location.href='index.php' is working?

I have the Index file like this 我有这样的索引文件

<?php
include('file1.php');
include('file2.php');
?>

in file1.php I am having the code like below. 在file1.php中,我有如下代码。

<?php
echo "hai";
?>

I am trying to redirect the page by using header('Location:index.php') .It throws an error something like the output already started.I know for header if we give the echo statement it throws an error.In this situation I am trying to redirect by using Javascript window.location.href='index.php' .It gives me the expected output and there is no error.Why?. 我试图通过使用header('Location:index.php')重定向页面,它会引发类似于已开始输出的错误。我知道对于header,如果我们给出echo语句会引发错误。我正在尝试使用Javascript window.location.href='index.php'进行重定向。它为我提供了预期的输出,并且没有错误。为什么?

The PHP header command is sending an instruction to the response stream that the browser will interpret as a redirect to a new location. PHP标头命令正在向响应流发送一条指令,浏览器会将其解释为重定向到新位置。 But, by its nature, you can only send a header of any kind before you has started sending content. 但是,从本质上讲,您只能在开始发送内容之前发送任何类型的标头。 In your example, you send the content "hai" then tried to send the header. 在您的示例中,您发送内容“ hai”,然后尝试发送标头。

Now your javascript is executed in the broswer by the javascript engine. 现在,您的javascript由javascript引擎在浏览器中执行。 As such, the window.location is telling the javascript engine to make the browser request a new page. 因此,window.location告诉javascript引擎使浏览器请求新页面。 This is independent of any information contained within the http stream (in theory, the location could be something other than http such as ftp or a mailto). 这与http流中包含的任何信息无关(理论上,该位置可以是http以外的其他内容,例如ftp或mailto)。

Try adding ob_start(); 尝试添加ob_start(); at the beginning of your PHP file. 在您的PHP文件的开头。 This will turn on output buffering, collecting all the output generated by your script and waiting til the end of execution before "flushing" the output to the browser. 这将打开输出缓冲,收集脚本生成的所有输出,并等到执行结束,然后再将输出“刷新”到浏览器。 You can force a flush using ob_end_flush(); 您可以使用ob_end_flush();强制刷新ob_end_flush();

More info: http://us3.php.net/ob_start 更多信息: http : //us3.php.net/ob_start

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM