Home >Backend Development >PHP Tutorial >Share the solution to the problem of carriage returns, line feeds and spaces in the ajax return value_PHP tutorial
I was writing a page recently, using jquery ajax to implement judgment. There was no problem with the test just after I wrote it. However, two days later I found a problem and the judgment could not be made. Later, I discovered that all alert return values will be preceded by a number of newlines and spaces. (I still don’t understand why such a problem occurs on the same computer and the same environment)
Later, I found on the Internet that someone had encountered the same problem. Whether it is jquery $.ajax $.get $.post or the original XMLHttpRequest method, there is this problem. When calling and judging, sometimes errors will occur. See example
ajax code:
ajax.php
Obviously, there is a newline or space in front of the string named google, which seriously affects the robustness of the program. I have encountered problems, and the judgments of the following program are not valid. Therefore we need to use regular expressions to remove it, so we can write like this
No need to change ajax.php
Then there will be no newline spaces.
Everything I see online uses
newData=data.replace(/rn/g,'');
But I found that this regular expression was problematic for me. Only a part of the whitespace characters were reduced in the front, so I judged that the whitespace characters should contain other whitespace characters except line feed and carriage return, so I chose s.
/.../g is an attribute of the regular expression, indicating full-text matching instead of stopping when one is found