JQuery Ajax in GBK encoded form submission Ultimate solution (non two-time coding method) _jquery

Source: Internet
Author: User
Tags serialization
Objective:
When jquery Ajax is under UTF-8 encoding (page utf-8, receive utf-8), there is no problem. You can post, get, and process the page directly to obtain the correct content.
But in the following cases:
GBK-> AJAX POST->GBK
UTF-8-> AJAX POST->GBK
Background code does not get the correct content, usually in the form of fetching strange characters and question marks.
Classic Solution:
1: Send the page, receive the page to use UTF-8 code.
2: Send the page before invoking the Ajax post method, the input containing Chinese content is encoded once with encodeuricomponent, and the receiving page calls the decoding method (for example: Java.net.urldecoder.decode ("Receive content", " Utf-8 ")).

Among them, the first method is undoubtedly the simplest, most direct, but often not realistic, because many projects are not using UTF-8 encoding, for example, most of the domestic use of GBK encoding, and can not solve such a problem, and the whole project to Utf-8 coding, the cost is too high, too risky.
The second method, is now most people use the method, commonly known as two times code, why call two times code, etc. will explain. Client code two times, service-side decoding two times. But this method is not good place, is the foreground manual code once, backstage again manual decoding once, a little inattentive will forget, and the code in front of the logic.
Interaction Process:
When we use forms to post submissions in the traditional way (non-AJAX submissions), the browser will be encoded according to the current page, encode once, and then sent to the server, the server received the form, will automatically dencode once, usually the process is transparent to the program, so plus manual encoding, decoding , it becomes the two-time code mentioned above.
But when we use Ajax to submit, the browser doesn't automatically encode us, so there's a piece of code in jquery:
 code as follows:

Ajax:function (s) {
Extend the settings, but Re-extend ' s ' So, 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);
........
}

This is the code snippet for the AJAX approach to jquery, and here's the code that calls the jquery Ajax post normally:
 code as follows:

$.ajax ({
Url:ajaxurl,
Type: ' POST ',
DataType: ' HTML ',
timeout:20000,//Timeout Time setting
data:para,//parameter settings
Success:function (HTML) {
}
});

As you can see from the above code, when you set the data, jquery calls the Jquery.param method to encode the parameters (perform the encode that should be handled by the browser).
 code as follows:

Jquery.param=function (a) {
var s = [];
function Add (key, value) {
s[S.length] = encodeURIComponent (key) + ' = ' + encodeuricomponent (value);
};
If an array being passed in, assume that it's 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, it ' s an object of key/value pairs
Else
Serialize the Key/values
for (Var j in a)
If The value is a 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


Workaround:



encodeURIComponent will be encoded in Utf-8, under GBK encoding, can you encode it with GBK?



If you are still playing encodeuricomponent idea, then sorry, encodeURIComponent will only utf-8 code, and no other API to do other coding; but don't worry, look at the following:



encodeURIComponent, it is to convert Chinese, Korean and other special characters into utf-8 format of the URL encoding.



Escape encodes a Unicode value other than 0-255 by outputting the%u**** format, in other cases the Escape,encodeuri,encodeuricomponent encoding results are the same.



Haha, see hope? Yes, it is to use escape instead of encodeURIComponent method, but must note:



Escape does not encode 69 characters: *,+,-,.,/,@,_,0-9,a-z,a-z



There are 71 encodeuricomponent characters that are not encoded:!, ', (,), *,-,.,_,~,0-9,a-z,a-z



When you use escape, you must encode the plus sign, otherwise, when the content contains the plus sign, it will be translated as a space by the server.



Finally know the workaround, rewrite the jquery code:


 code as follows:

Jquery.param=function (a) {
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 being passed in, assume that it's 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, it ' s an object of key/value pairs
Else
Serialize the Key/values
for (Var j in a)
If The value is a 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 jquery's source file, it can be pasted on your project's JavaScript, overwriting its original method, but must be done after jquery has been loaded.

After preliminary verification, the above code in the Utf-8 coding can also work properly, probably encoded into Unicode for the sake of it.

In this way, it is not necessary to use what two times coding, that is, affect the foreground, but also affect the background. GBK Encoding Ajax post is no longer a problem, this is the ultimate solution. Ha ha.

Interested can go to http://www.open-lib.com/Forum/Read_69_1.action to communicate with the author.
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.