开发者

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

开发者 https://www.devze.com 2023-03-31 06:10 出处:网络
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.

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, I want to compare the string in the responseText to see if it is == to "yes" (or "no"). But the comparison fails.

So I do the alert responseText, and it does show "yes" (or "no") as the string. But I read on here that the responseText might contain hidden whitespace characters, so I did the string length of responseText and it shows that the string length is 4 characters longer than what it should be. So I escaped the responseText alert(escape(responseText)) and it shows that I have %0A and %0D (newlines and line feeds) hidden at the end of the responseText string.

I read that these characters are added on by php, but I also read that the extra characters are different among different php versions/servers.

How to prevent these extra whi开发者_运维问答tespaces without using regex, since regex might remove intentional whitespaces?

Please don't suggest using jquery or mootools as answers.

TIA


I read that these characters are added on by php, but I also read that the extra characters are different among different php versions/servers.

That's wrong. That's simple to verify: create a test.php file, write this and only this: <?php echo "test"; (without ?>) into it and execute it. There will be no whitespace.

These whitespaces most probably come from your scripts. A common error is to leave some trailing newlines after a closing php tags (?>), which results in a new line being printed.

Verify that all files included before or after you do echo "yes"; don't echo anything and don't have a trailing newline after a ?>.

The easiest way to avoid this problem is do not use php close tags at end of files (they are not mandatory).


I know you asked about doing the comparison without regexes, but given the conditions you mentioned above, that's going to be a very quick and effective way to get your answer, and won't necessarily perturb any other processing.

var trimmedResponse = responseText.replace(/^\s*/,'').replace(/\s*$/,'').toLowerCase();
if (trimmedResponse == 'yes') {
  // do your 'yes' case
} else if (trimmedResponse == 'no') {
  // do your 'no' case
} else {
  // do your 'none of the above' case
}

That's going to trim off leading white space, trailing white space (including the CR/LF combo), and convert to lower case just for comparison.


I think you may be going at it the wrong way. Instead of manually trying to create a response why don´t you use PHP arrays as a data structure and JSON for delivery?

<?php
$flag = false
if (condition){
  $flag = true;
}

$arr = array("is_true" => $flag)
$json = json_encode($arr);

// See http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/
// Set JSONP header
header('content-type: application/json; charset=utf-8');

// Get callback from $_GET and prepend the JSON data
echo isset($_GET['callback'])
    ? "{$_GET['callback']}($json)"
    : $json;


Did you try using PHP's trim() function before sending the data?


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;


In my case I solved this problem by removing spaces between two php blocks in same php file ( "...? > < ?php..." ) which it requires by require_once() method.

<?php 
  //your code
?>
*this space might appear in the XHTTP responce*
<?php 
  //your code
?>

--OR-- you can send your data as JSON Object from the server script (php) , for this you can use json_encode() . for the client side (javascript) you may use eval(this.responce) .

0

精彩评论

暂无评论...
验证码 换一张
取 消