开发者

Why are my "+" characters turned into spaces in my CGI program that handles Ajax requests?

I'm collecting text through a web form and noticing that when it is collected by my Perl CGI all instances of "+" are transformed in开发者_如何学编程to " ". I run the text through a JavaScript escape before submission, but escape seems to leave + unaltered.

There must be something really obvious that I'm missing... how do I send the string "2 + 2 = 4" through and not have it arrive as "2 2 = 4"?


The escape and unescape functions do not work properly for non-ASCII characters and have been deprecated. In JavaScript 1.5 and later, use encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent.

— https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Predefined_Functions/escape_and_unescape_Functions

Replace escape with encodeURIComponent


You '+', in the URL, should be encoded as %2B :

http://www.example.com/myscript.ext?a=2%20%2B%202%20=%204

Will give a = 2 + 2 = 4


In Javascript, this means using the encodeURIComponent function : this portion of code :

encodeURIComponent('2 + 2 = 4')

will give :

"2%20%2B%202%20%3D%204"

Note the + is encoded.


While this one :

escape('2 + 2 = 4')

would only give :

"2%20+%202%20%3D%204"

Note the + is not encoded.


You can encode + as %2B, as seen in: http://www.google.com/search?q=2+%2B+2


I do not know what you mean by using JavaScript escape. Browsers will properly encode form field values and CGI.pm will properly decode them.

For example,

#!/usr/bin/perl

use strict; use warnings;
use CGI;

my $cgi = CGI->new;

if ( $cgi->param ) {
    process_form($cgi);
}
else {
    show_form($cgi);
}

sub process_form {
    my ($cgi) = @_;

    print $cgi->header('text/plain'),
          $cgi->param('entry'), "\n";
}
sub show_form {
    my ($cgi) = @_;

    print $cgi->header, <<EO_HTML;
<!DOCTYPE HTML>
<html><head><title>Test +</title></head>
<body><form>
<input name="entry"><input type="submit">
</form></body></html>
EO_HTML
}

The output I get from submitting this form with 2+2=4 in the entry field is:

2+2=4
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜