的responseText包含额外的空格字符(新线,换行),如何prevent并删除它们?新线、空格、换行、字符

2023-09-10 18:59:59 作者:伱的愛、卜濄茹此

我有一个调用PHP文件的AJAX脚本。

PHP文件回声报是或不是,我想用字符串做逻辑比较。

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

所以,我做的警报responseText的,而且它确实显示出是(或否)作为字符串。但我读这里的responseText的可能含有隐藏的空白字符,所以我做的responseText的字符串的长度,这表明该字符串的长度是比它要长4个字符。所以,我躲过了responseText的警报(越狱(responseText的)),它表明我有%0A和0D%(换行和换行)隐藏在responseText的字符串的结尾。

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

如何prevent不使用正则表达式这些额外的空格,因为正则表达式可能会删除故意空格?

请不要建议使用jQuery或MooTools的作为答案。

TIA

解决方案   

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

条码数字中额外的空格如何操作

这是错误的。这是简单的验证:创建一个test.php的文件,写这篇文章,只有这样:< PHP的回声测试; (不含&GT? ; )到它并执行它。不会有空格。

这些空格最有可能来自你的脚本。一个常见的​​错误是一个PHP结束标记之后留下一些尾随换行符(> ),这将导致一个新的生产线正在打印

确认包括所有文件之前或之后你做回声是; 不回应任何事情,没有一个>

要避免这一问题的最简单的方法是不使用PHP的关闭标签,在文件的结尾(他们是不是强制性的)。

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

解决方案

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).