responseText contains extra whitespace characters (new lines, line feeds), how to prevent and remove them?

前端 未结 6 550
忘了有多久
忘了有多久 2021-01-03 13:17

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,

6条回答
  •  感情败类
    2021-01-03 13:41

    Even if it's possible to look after all PHP script to avoid CRLF before or after php tag, this is not a good option as you can imagine adding in a few days, or month or years (without wanting!) a CRLF in a file and this will impact another part of your web site.

    In fact, to avoid this problem you have two options:

    Option 1: Let php send the data so with the garbage at beginning, and clean the data in Javascrpt with:

     response = http.responseText;
     response = response.replace(/[\n\r]+/g, '');
    

    In this case this means you clean ALL the CRLF (change the Regex to clean only at beginning if needed or to clean also spaces)

    Option 2 (better I think) is to clean the output buffer of PHP immediatly before sending the data to browser. So:

     ... many code here
     ob_end_clean();
     echo $data_for_the_browser;
    

提交回复
热议问题