JQuery Ajax under GBK encoding form Submission Ultimate solution (not two-time encoding method) (RPM)

Source: Internet
Author: User

Copyright Notice]: Copyright is the author of all, reproduced in the form of hyperlinks to the original source of the article and the author information and this statement:
Http://www.open-lib.com/Forum/Read_69_1.action

Objective:

When jquery Ajax is encoded under UTF-8 (page utf-8, receiving utf-8), there is no problem. You can get the correct content directly from the post, get, and process pages.

However, in the following cases:

GBK AJAX POST->GBK

UTF-8 AJAX POST->GBK

Background code cannot get the correct content, usually in the form of getting strange characters, question marks.

Classic Solution:

1: Send the page, receive the page to use UTF-8 encoding.

2: Send page before calling the Ajax post method, the input containing Chinese content is encoded once with encodeuricomponent, while the receiving page calls the decoding method (for example: Java.net.urldecoder.decode ("Receive content", " Utf-8 ")).


The first method is undoubtedly the simplest, most direct, but often not realistic, because many projects do not use UTF-8 encoding, for example, most of the domestic use of GBK coding, it is impossible to solve such a problem, and the whole project into Utf-8 coding, the cost is too high, the risk is too great.

The second method, is now the most people use the method, commonly known as two times code, why called two times the code, and so on will explain. The client encodes two times and the server decodes two times. But this method is not good place, is the front desk manually coded once, the background and then manually decoded once, a little inattentive will forget, and the code in front of the logic.

Interactive process:

When we use the form in the traditional way of post submission (non-AJAX submissions), the browser will be based on the current page encoding, encode once, and then sent to the server, the server received the form, will automatically dencode once, usually this process is transparent to the program, so add manual encoding, decoding , it becomes the two-time code mentioned above.

But when we use Ajax to submit, the browser does not automatically encode us, so there is a piece of code in jquery:

Ajax:function (s) {//Extend the settings, but Re-extend ' s'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 stringif (S.data && S.proc Essdata && typeof s.data!== "string") S.data = Jquery.param (S.data); ...}

The above is the code snippet for the Ajax method of jquery, here is the code for calling jquery Ajax post normally:

$.ajax ({url:ajaxurl, type: ' POST ', DataType: ' HTML ', timeout:20000,//time-out setting data:para,//parameter settings success:function (HTML) {} });

As you can tell by the above code, when data is set, jquery internally calls the Jquery.param method to the parameter encode (performing the encode that should have been handled by the browser).

jquery.param=function (a) {var s = [];function Add ( Key, value) {s[s.length] = encodeURIComponent (key) + ' = ' + encodeuricomponent (value);};/  /If An array were passed in, assume, it's an array//of form elementsif (Jquery.isarray (a) | | a.jquery)//Serialize The form Elementsjquery.each (A, function () {Add (this.name, this.value);});  /Otherwise, assume that it's an object of Key/value pairselse//Serialize the Key/valuesfor (Var j in a)//If the value is a array then the key names need to being Repeatedif (Jquery.isarray (A[j])) Jquery.each (A[j], function () {Add (J, this) ;}); Elseadd (J, Jquery.isfunction (A[j])? A[j] (): a[j]);//Return The resulting Serializationreturn s.join ("&"). Replace ( /%20/g, "+");} Jquery.param End 

The above is Jquery.param code, the careful point can notice encodeuricomponent This method, this is the JavaScript built-in method, executes the utf-8 encode to the target string, therefore, when the page uses the GBK encoding, The server will use GBK to decode, but the actual data submitted is encoded in Utf-8, so the received content is garbled or a question mark .

Workaround:

encodeURIComponent will utf-8 code, under GBK code, can I encode it by GBK?

If still playing encodeuricomponent idea, that embarrassed, encodeURIComponent will only utf-8 code, and no other API for other coding; but, don't worry, look at the following:

encodeURIComponent, which is a URL encoding that converts special characters, such as Chinese and Korean, into the utf-8 format.

Escape outputs the%u**** format when encoding Unicode values other than 0-255, and in other cases the Escape,encodeuri,encodeuricomponent encoding results are the same.

Haha, see hope? Yes, it is to replace the encodeURIComponent method with escape, but it must be noted that:

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

encodeURIComponent does not encode 71 characters:!, ', (,), *,-,.,_,~,0-9,a-z,a-z

The plus sign must be encoded after using escape, otherwise the service side will be translated as a space when the content contains a plus sign.

Finally know the solution, rewrite the jquery code:

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 were passed in, assume, it's an array//of form elementsif (Jquery.isarray (a) | | a.jquery)//Serialize The form Elementsjquery.each (A, function () {Add (this.name, this.value);});  /Otherwise, assume that it's an object of Key/value pairselse//Serialize the Key/valuesfor (Var j in a)//If the value is a array then the key names need to being Repeatedif (Jquery.isarray (A[j])) Jquery.each (A[j], function () {Add (J, this) ;}); Elseadd (J, Jquery.isfunction (A[j])? A[j] (): a[j]);//Return The resulting Serializationreturn s.join ("&"). Replace ( /%20/g, "+");}

The above code does not need to be rewritten in the jquery source file, it can overwrite the original method on your project's JavaScript, but it must be after jquery is loaded.

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

In this way, it is not necessary to use what two times code, 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.

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.