Ajax return values include line breaks and spaces.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.