Ajax responseText和echo已损坏,返回头文件内容


Ajax responseText and echo broken, returning header file contents

我在hpFile.php文件中有以下代码来处理Ajax调用:

<?php
    require_once('usefulStuff.php'); // stuff used throughout the code 
if (isset($_GET['zer']))
{
   $bFound = false;

  if(! $bFound)
  {
     echo "notfound";
     return;
  }   
  else 
  {
      echo "found";
      return;
  }
}
?>

以下是处理responseText:的内联onreadystate函数(javascript)

var theResponseText = "rText";
var zer = "testing";
xmlhttp.onreadystatechange = function()
{
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        theResponseText = xmlhttp.responseText;
        alert("responseText is >>>" + theResponseText + "<<< that.");
        if( theResponseText == 'notfound')
        {
            alert("sorry, nothing found.")
        }
    }
}
var ajaxText = "thePhpFile.php?zer=" + zer;
xmlhttp.open("GET", ajaxText, false);
xmlhttp.send();

如果我在我的usefulStuff.php include文件中添加换行符或其他任何内容,并且我将其添加到usefulStuff.php的底部,之后?>结束标记——上面的下面一行代码,一个echo语句,会特意查找和获取那些额外的换行符等,并在我的responseText:中返回它们

 echo "notfound";

在编写了一个编译器并处理了BNF语法之后,我不明白为什么php中的echo语句被设置为"echo",而不仅仅是"echo’"后面到第一个分号";"在解析过程中遇到的。

我知道我可以使用trim()来撤消空白,但我的问题是,我想强制上面的echo语句按照上面echo语法建议的方式进行操作。如果上面的echo语句在我的include文件中四处寻找无关的空白以返回"未找到"文本是有充分理由的,我不知道这是什么原因,但我想禁用这种意外行为。

我想要我的代码行echo"notfound"只需回显单词notfound,并在"notfound"文本后立即遇到分号时停止回显。

如何将echo行为限制为仅回显单词回声后面的内容,并在达到分号时停止回显?

顺便说一句,在试验我的usefulStuff.php文件的内容时,这些内容不在?>终止标签,我在该文件的末尾添加了这个:

 // now ending the php code in usefuleStuff.php:
?>
<noscript>
   <meta http-equiv="refresh" content="0; 
         URL=http://mywebsite.com/noscript.html"/>
</noscript>

代码行echo"notfound"——当我检索responseText时——响应文本除了包含我的"notfound"之外,还包含所有三行noscript代码,以及任何额外的空白。

因此,php中的"echo"是垃圾收集我放在所包含的usefulStuff.php文件末尾的任何内容。

如何将echo的行为限制为执行代码行echo"notfound"会让你相信它会起作用,也就是说,只回应单词"notfound"?

我偶然发现了一个问题的解决方案,那就是我如何使语句echo"notfound"在Ajax调用中执行语法所建议的操作——我很欣赏解释"为什么"我得到了简单代码行echo"notfound"的额外内容乍一看并没有暗示会发生。

以下是我如何强迫echo"notfound;**的语法做它看起来应该做的事情,即发送单词notfound[/strong>作为我的responseText,而不是其他任何东西——我在一篇高度边缘化的帖子中偶然发现了这一点,该帖子只提到了php函数"ob_end_clean()",我从那里得到了它。

这是我修改后的代码,它返回一个严格控制的数据块作为我的Ajax响应文本:

<?php
require_once('usefulStuff.php'); // stuff used throughout the code 
if (isset($_GET['zer']))
{
   $bFound = false;

   if(! $bFound)
   {
      ob_end_clean();
      ob_start();
      echo "notfound";
      ob_end_flush();
      return;
   }   
   else 
   {
      echo "found";
      return;
   }
}
?>

为了验证这一点,我在usefulStuff.php文件的最后放了十行换行符和下面的代码,不在结束的?>标签:

   // now ending the php code in usefulStuff.php:
   ?>
    // ten newlines here....
   <noscript>
        <meta http-equiv="refresh" content="0; 
              URL=http://mywebsite.com/noscript.html"/>
   </noscript>

现在,不管我的结束语之外有任何代码或空白?>hp标记——我的Ajax onreadystatechange函数中的responseText完全包含我期望的内容,"notfound",而没有其他内容

自从20世纪80年代和90年代初的C编程时代以来,我就没有使用过输出缓冲函数。这是我第一次使用php的输出缓冲函数,但它确实让我能够很好地控制我的responseText在Ajax调用中的样子。