responseText包含额外的空白字符(换行、换行),如何防止和删除它们?

发布于 2024-12-01 15:35:25 字数 506 浏览 0 评论 0原文

我有一个调用 php 文件的 ajax 脚本。

php文件回显“是”或“否”,我想使用字符串进行逻辑比较。

在javascript中,我想比较responseText中的字符串,看看它是否==到“是”(或“否”)。但比较失败。

所以我做了警报响应文本,它确实显示“是”(或“否”)作为字符串。但我在这里读到responseText可能包含隐藏的空白字符,所以我计算了responseText的字符串长度,它显示字符串长度比应有的长度多了4个字符。所以我转义了responseText警报(escape(responseText)),它显示我在responseText字符串的末尾隐藏了%0A和%0D(换行符和换行符)。

我读到这些字符是由 php 添加的,但我也读到不同的 php 版本/服务器之间的额外字符是不同的。

由于正则表达式可能会删除有意的空格,因此如何在不使用正则表达式的情况下防止这些额外的空格?

请不要建议使用 jquery 或 mootools 作为答案。

TIA

I have an ajax script that calls a php file.

The php file echos "yes" or "no", I want to use the strings to do logical comparisons.

In the javascript, I want to compare the string in the responseText to see if it is == to "yes" (or "no"). But the comparison fails.

So I do the alert responseText, and it does show "yes" (or "no") as the string. But I read on here that the responseText might contain hidden whitespace characters, so I did the string length of responseText and it shows that the string length is 4 characters longer than what it should be. So I escaped the responseText alert(escape(responseText)) and it shows that I have %0A and %0D (newlines and line feeds) hidden at the end of the responseText string.

I read that these characters are added on by php, but I also read that the extra characters are different among different php versions/servers.

How to prevent these extra whitespaces without using regex, since regex might remove intentional whitespaces?

Please don't suggest using jquery or mootools as answers.

TIA

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

抽个烟儿 2024-12-08 15:35:25

我读到这些字符是由 php 添加的,但我也读到不同的 php 版本/服务器之间的额外字符是不同的。

那是错误的。验证起来很简单:创建一个 test.php 文件,只写入以下内容: (不带 ?>) 并写入其中执行它。不会有空格。

这些空格很可能来自您的脚本。一个常见的错误是在关闭 php 标签 (?>) 后留下一些尾随换行符,这会导致打印新行。

验证执行 echo "yes"; 之前或之后包含的所有文件是否不回显任何内容,并且在 ?> 之后没有尾随换行符。

避免此问题的最简单方法是不要在文件末尾使用 php 关闭标记(它们不是强制性的)。

I read that these characters are added on by php, but I also read that the extra characters are different among different php versions/servers.

That's wrong. That's simple to verify: create a test.php file, write this and only this: <?php echo "test"; (without ?>) into it and execute it. There will be no whitespace.

These whitespaces most probably come from your scripts. A common error is to leave some trailing newlines after a closing php tags (?>), which results in a new line being printed.

Verify that all files included before or after you do echo "yes"; don't echo anything and don't have a trailing newline after a ?>.

The easiest way to avoid this problem is do not use php close tags at end of files (they are not mandatory).

南城旧梦 2024-12-08 15:35:25

我知道您询问是否在没有正则表达式的情况下进行比较,但考虑到您上面提到的条件,这将是获得答案的非常快速且有效的方法,并且不一定会干扰任何其他处理。

var trimmedResponse = responseText.replace(/^\s*/,'').replace(/\s*$/,'').toLowerCase();
if (trimmedResponse == 'yes') {
  // do your 'yes' case
} else if (trimmedResponse == 'no') {
  // do your 'no' case
} else {
  // do your 'none of the above' case
}

这将修剪掉前导空白、尾随空白(包括 CR/LF 组合),并转换为小写以进行比较。

I know you asked about doing the comparison without regexes, but given the conditions you mentioned above, that's going to be a very quick and effective way to get your answer, and won't necessarily perturb any other processing.

var trimmedResponse = responseText.replace(/^\s*/,'').replace(/\s*$/,'').toLowerCase();
if (trimmedResponse == 'yes') {
  // do your 'yes' case
} else if (trimmedResponse == 'no') {
  // do your 'no' case
} else {
  // do your 'none of the above' case
}

That's going to trim off leading white space, trailing white space (including the CR/LF combo), and convert to lower case just for comparison.

葵雨 2024-12-08 15:35:25

我认为你可能采取了错误的方式。为什么不使用 PHP 数组作为数据结构并使用 JSON 进行传递,而不是手动尝试创建响应?

<?php
$flag = false
if (condition){
  $flag = true;
}

$arr = array("is_true" => $flag)
$json = json_encode($arr);

// See http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/
// Set JSONP header
header('content-type: application/json; charset=utf-8');

// Get callback from $_GET and prepend the JSON data
echo isset($_GET['callback'])
    ? "{$_GET['callback']}($json)"
    : $json;

I think you may be going at it the wrong way. Instead of manually trying to create a response why don´t you use PHP arrays as a data structure and JSON for delivery?

<?php
$flag = false
if (condition){
  $flag = true;
}

$arr = array("is_true" => $flag)
$json = json_encode($arr);

// See http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/
// Set JSONP header
header('content-type: application/json; charset=utf-8');

// Get callback from $_GET and prepend the JSON data
echo isset($_GET['callback'])
    ? "{$_GET['callback']}($json)"
    : $json;
梦里的微风 2024-12-08 15:35:25

即使可以照顾所有 PHP 脚本以避免 php 标记之前或之后的 CRLF,这也不是一个好的选择,因为您可以想象在几天、几个月或几年内(不需要!)在文件中添加 CRLF,并且这将影响您网站的其他部分。

事实上,为了避免这个问题,你有两个选择:

选项 1:让 php 以垃圾开头发送数据,然后清理 Javascrpt 中的数据:

 response = http.responseText;
 response = response.replace(/[\n\r]+/g, '');

在这种情况下,这意味着你清理所有数据CRLF(将正则表达式更改为仅在需要时才清理或也清理空格)

选项 2(我认为更好)是在将数据发送到浏览器之前立即清理 PHP 的输出缓冲区。所以:

 ... many code here
 ob_end_clean();
 echo $data_for_the_browser;

Even if it's possible to look after all PHP script to avoid CRLF before or after php tag, this is not a good option as you can imagine adding in a few days, or month or years (without wanting!) a CRLF in a file and this will impact another part of your web site.

In fact, to avoid this problem you have two options:

Option 1: Let php send the data so with the garbage at beginning, and clean the data in Javascrpt with:

 response = http.responseText;
 response = response.replace(/[\n\r]+/g, '');

In this case this means you clean ALL the CRLF (change the Regex to clean only at beginning if needed or to clean also spaces)

Option 2 (better I think) is to clean the output buffer of PHP immediatly before sending the data to browser. So:

 ... many code here
 ob_end_clean();
 echo $data_for_the_browser;
愛放△進行李 2024-12-08 15:35:25

在发送数据之前,您是否尝试使用 PHP 的 trim() 函数?

Did you try using PHP's trim() function before sending the data?

你的背包 2024-12-08 15:35:25

就我而言,我通过删除同一 php 文件中两个 php 块之间的空格解决了这个问题 ( "...? > < ?php... " ),这是 require_once() 方法所需要的。

<?php 
  //your code
?>
*this space might appear in the XHTTP responce*
<?php 
  //your code
?>

- 或者 -
您可以从服务器脚本 (php) 将数据作为 JSON 对象发送,为此您可以使用 json_encode() 。对于客户端(javascript),您可以使用 eval(this.responce)

In my case I solved this problem by removing spaces between two php blocks in same php file ( "...? > < ?php..." ) which it requires by require_once() method.

<?php 
  //your code
?>
*this space might appear in the XHTTP responce*
<?php 
  //your code
?>

--OR--
you can send your data as JSON Object from the server script (php) , for this you can use json_encode() . for the client side (javascript) you may use eval(this.responce) .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文