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

Share the solution to the problem of carriage returns, line feeds and spaces in the ajax return value_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:25:57883browse

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:

Copy code The code is as follows:

$.get('ajax.php',{'name':name}, function(data){
alert(data);
})

ajax.php

Copy code The code is as follows:

$username = $_GET['name'];
echo $username;
?>

Share the solution to the problem of carriage returns, line feeds and spaces in the ajax return value_PHP tutorial

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

Copy code 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

Share the solution to the problem of carriage returns, line feeds and spaces in the ajax return value_PHP tutorial

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824875.htmlTechArticleI am writing a page recently, using jquery ajax to implement judgment. I just wrote the test and there is no problem at all. After two days Tian discovered that there was a problem and could not make a judgment. Later I found that all alerts returned...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn