This article describes how to solve ajax return values with line breaks and spaces. if you need them, refer to the recently written page and use jquery ajax for judgment, there was no problem in writing the test just now. After two days, I found the problem could not be determined. Later, we found that some line breaks and spaces are added before the returned values of alert. (Why is there such a problem in the same computer and environment)
Later, I found that some people encountered the same problem on the Internet. This problem exists in jquery $. ajax $. get $. post, or in the XMLHttpRequest method of the original sound. in this way, errors may occur during call and judgment. Look at the example
Ajax code:
The code is as follows:
$. Get ('Ajax. php', {'name': name}, function (data ){
Alert (data );
})
Ajax. php
The code is as follows:
$ Username = $ _ GET ['name'];
Echo $ username;
?>
Obviously, there are line breaks or spaces in front of the string whose name is google. This seriously affects the robustness of the program. I have encountered problems and the judgment of the following programs is not true. Therefore, we need to use the regular expression method to remove it, so we can write
The code is as follows:
$. Get ('Ajax. php', {'name': name}, function (data ){
NewData = data. replace (/\ s/g ,'');
Alert (newData );
})
No need to change ajax. php
Then there is no line break space.
All I see on the Internet are
NewData = data. replace (/rn/g ,'');
However, I found that this regular expression is incorrect for me. I only removed some white space characters in the front. Therefore, I have determined that there should be other white spaces except line breaks and carriage returns, s is selected.
/.../G is the attribute of the regular expression, indicating full-text matching, instead of stopping when one is found.