1

我的 thePhpFile.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();

如果我真的在我的有用Stuff.php 包含文件中添加换行符或其他任何东西 - 我将它添加到有用Stuff.php 的底部,在>结束标记之后 - 上面的以下代码行,回声语句,不遗余力地定位和抓取那些额外的换行符等,并将它们返回到我的 responseText 中:

 echo "notfound";

编写了编译器并处理了 BNF 语法后,我不明白为什么 php 中的 echo 语句设置为“回显”,而不是紧跟在“回显”之后直到第一个分号“;”。在解析过程中遇到。

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

我希望我的代码行 回显“未找到”;仅此而已 - 只需回显单词notfound并在“notfound”文本之后立即遇到分号时停止回显。

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

顺便说一句,在试验我的有用Stuff.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 时 - 响应文本还包含所有三个noscript代码行,加上任何额外的空格,除了我的“notfound”。

所以 php 中的“回声”是垃圾收集我在包含的有用Stuff.php 文件末尾放置的任何内容。

如何限制 echo 的行为以执行代码echo "notfound" 的行为;让你相信它会做,也就是说,只回显“notfound”这个词?

4

1 回答 1

2

我偶然发现了我的问题的解决方案,即如何使声明回显“未找到”;在 Ajax 调用中,完全按照语法似乎建议的那样做——我很欣赏“为什么”的解释,我得到了额外的东西,简单的代码行回显“未找到”;乍一看并不认为会发生。

以下是我如何强制使用 echo "notfound ;** 的语法来做它应该做的事情,即将单词notfound作为我的 responseText 发送,仅此而已——我是从一个高度外围相关的帖子中偶然发现的那只提到了php函数'ob_end_clean()',我从那里拿走了它。

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

<?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;
   }
}
?>

为了验证这是否有效,我在我的有用Stuff.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>

现在,不管我的有用Stuff.php 包含文件中的关闭?> php 标记之外的任何代码或空格是什么——我的 Ajax onreadystatechange 函数中的 responseText 包含的正是我所期望的,“未找到”,仅此而已。

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

于 2013-08-09T06:38:34.253 回答