JQuery ajax final solution for form submission in GBK encoding (non-quadratic encoding)

Source: Internet
Author: User

Preface:

When jquery ajax is encoded in UTF-8 (page UTF-8, receives UTF-8), there is no problem. You can post and get the correct content directly on the processing page.

However, in the following cases:

GBK-> ajax post-> GBK

UTF-8-> ajax post-> GBK

The background Code cannot obtain the correct content, which is usually indicated by getting strange characters and question marks.

Classic solution:

1: Send page, receive page are UTF-8 encoding.

2: Before calling the ajax post method, the sending page uses encodeURIComponent to encode the input containing Chinese content, and the receiving page calls the decoding method (for example, java.net. urldecoder. decode ("received content", "UTF-8 ")).


Among them, the first method is undoubtedly the simplest and most direct, but it is often not practical, because many projects do not use UTF-8 encoding, for example, most domestic use of gbk encoding, it is impossible to convert the entire project into UTF-8 encoding to solve this problem, which is costly and risky.

The second method is the method currently used by most people, commonly known as quadratic encoding. Why is it called quadratic encoding? I will explain it later. The client is encoded twice and decoded twice by the server. But this method is not good, that is, the front-end manual encoding, and the background manual decoding, will be forgotten, and the code is mixed with the front-end logic.

Interaction Process:

When we use a form for post submission in the traditional mode (non-AJAX submission), the browser will encode the current page, encode once, and then send it to the server. The server will receive the form and automatically dencode it once, this process is usually transparent to the program, so the manual encoding and decoding will become the second encoding mentioned above.

However, when we use AJAX for submission, the browser does not automatically replace our encode, so there is such a piece of code in jquery:


Ajax: function (s ){
// Extend the settings, but re-extend's 'so that it can be
// Checked again later (in the test suite, specifically)
S = jQuery. extend (true, s, jQuery. extend (true, {}, jQuery. ajaxSettings, s ));
 
Var jsonp, jsre =/=? (& | $)/G, status, data,
Type = s. type. toUpperCase ();
 
// Convert data if not already a string
If (s. data & s. processData & typeof s. data! = "String ")
S. data = jQuery. param (s. data );
........
}
The above is the code snippet of jquery's ajax method. below is the code that calls jquery ajax post normally:


$. Ajax ({
Url: ajaxurl,
Type: 'post ',
DataType: 'html ',
Timeout: 20000, // timeout value
Data: para, // parameter settings
Success: function (html ){
 
}
});
The code above shows that when data is set, jquery calls the jQuery. param method internally to encode the parameter (execute the encode that should be processed by the browser ).


JQuery. param = function (){
Var s = [];
Function add (key, value ){
S [s. length] = encodeURIComponent (key) + '=' + encodeURIComponent (value );
};
// If an array was passed in, assume that it is an array
// Of form elements
If (jQuery. isArray (a) | a. jquery)
// Serialize the form elements
JQuery. each (a, function (){
Add (this. name, this. value );
});
 
// Otherwise, assume that it's an object of key/value pairs
Else
// Serialize the key/values
For (var j in)
// If the value is an array then the key names need to be repeated
If (jQuery. isArray (a [j])
JQuery. each (a [j], function (){
Add (j, this );
});
Else
Add (j, jQuery. isFunction (a [j])? A [j] (): a [j]);
 
// Return the resulting serialization
Return s. join ("&"). replace (/% 20/g, "+ ");
} // Jquery. param end
The above is jQuery. the Code of param. Pay attention to the encodeURIComponent method. This is a built-in javascript method that executes UTF-8 encode on the target string. Therefore, when the page uses gbk encoding, the server uses gbk for decoding, but the actually submitted data is encoded in UTF-8 format. As a result, the received content is garbled or a question mark.

Solution:

EncodeURIComponent is UTF-8 encoded. Can it be encoded with gbk in gbk encoding?

If you are still playing the encodeURIComponent idea, I am sorry. encodeURIComponent only uses UTF-8 encoding and does not use other APIs for encoding. However, don't worry. Let's take a look at the following:

EncodeURIComponent converts special characters such as Chinese and Korean into UTF-8 url encoding.

When encoding unicode values other than 0-, escape outputs % u *** format. In other cases, escape, encodeURI, and encodeURIComponent have the same encoding result.

Haha, Hope? Yes, it is to replace encodeURIComponent with escape, but note the following:

Escape unencoded characters are 69: *, +,-,.,/, @, _, 0-9, a-z, A-Z

EncodeURIComponent has 71 unencoded characters :!, ',(,),*,-,.,_,~, 0-9, a-z, A-Z

After escape is used, the plus sign must be encoded. Otherwise, when the content contains the plus sign, it is translated as a space by the server.

Finally, we know the solution. Rewrite the jquery code:


JQuery. param = function (){
Var s = [];
Var encode = function (str ){
Str = escape (str );
Str = str. replace (/+/g, "% u002B ");
Return str;
};
Function add (key, value ){
S [s. length] = encode (key) + '=' + encode (value );
};
// If an array was passed in, assume that it is an array
// Of form elements
If (jQuery. isArray (a) | a. jquery)
// Serialize the form elements
JQuery. each (a, function (){
Add (this. name, this. value );
});
 
// Otherwise, assume that it's an object of key/value pairs
Else
// Serialize the key/values
For (var j in)
// If the value is an array then the key names need to be repeated
If (jQuery. isArray (a [j])
JQuery. each (a [j], function (){
Add (j, this );
});
Else
Add (j, jQuery. isFunction (a [j])? A [j] (): a [j]);
 
// Return the resulting serialization
Return s. join ("&"). replace (/% 20/g, "+ ");
}
The above Code does not need to be rewritten in the jquery source file. You can paste it in the javascript of your project to overwrite its original method, but it must be loaded after jquery.

After preliminary verification, the above Code can also work normally in UTF-8 encoding, probably because it is encoded into unicode.

In this way, there is no need to use any secondary encoding, that is, it affects the foreground and the background. Under gbk encoding, ajax post is no longer a problem. This is the ultimate solution. Haha.


From Hurry's column

Related Article

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.