Home > Web Front-end > JS Tutorial > The ultimate solution for jQuery ajax form submission under GBK encoding (non-secondary encoding method)_jquery

The ultimate solution for jQuery ajax form submission under GBK encoding (non-secondary encoding method)_jquery

WBOY
Release: 2016-05-16 18:18:16
Original
1161 people have browsed it
Foreword:
When jquery ajax is encoded in utf-8 (page utf-8, receive utf-8), there is no problem. You can post and get normally, and process the page to directly obtain the correct content.
But in the following cases:
GBK -> AJAX POST ->GBK
UTF-8 -> AJAX POST ->GBK
The code behind cannot get the correct content, which usually behaves To get strange characters, question marks.
Classic solution:
1: Both the sending page and the receiving page use UTF-8 encoding.
2: Before calling the ajax post method on the sending page, encode the input containing Chinese content once with encodeURIComponent, while the receiving page calls the decoding method (such as: java.net.urldecoder.decode("Content received"," utf-8") ).

Among them, the first method is undoubtedly the simplest and most direct, but it is often unrealistic because many projects do not use utf-8 encoding. For example, most of the country uses gbk encoding, and it is impossible to solve the problem. For such a problem, converting the entire project to UTF-8 encoding is too costly and risky.
The second method is the method used by most people now. It is commonly known as secondary encoding. Why it is called secondary encoding will be explained later. The client encodes twice and the server decodes twice. But the disadvantage of this method is that it is manually coded once in the frontend and decoded manually in the backend. If you are not careful, you will forget it, and the code is mixed with the frontend logic.
Interaction process:
When we use the form to post and submit in the traditional way (non-AJAX submission), the browser will encode according to the current page, encode it once, and then send it to the server. When the server receives the form, it will automatically Dencode once, usually this process is transparent to the program, so with manual encoding and decoding, it becomes the secondary encoding mentioned above.
But when we submit using AJAX, the browser will not automatically encode for us, so there is a piece of code like this in jquery:
Copy code The code is as follows:

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. The following is the code for calling jquery ajax post normally:
Copy code The code is as follows:

$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'html',
timeout: 20000 ,//Timeout setting
data:para,//Parameter setting
success: function(html){
}
});

Through the above code It can be known that when data is set, jquery will internally call the jQuery.param method to encode the parameters (perform the encode that should be processed by the browser).
Copy code The code is as follows:

jQuery.param=function( a ) {
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 a )
// 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(/ /g, " " );
}//jquery.param end

Solution:

encodeURIComponent will be encoded in utf-8. Under gbk encoding, can it be encoded in gbk?

If you are still thinking about encodeURIComponent, sorry, encodeURIComponent can only encode utf-8, and there is no other API for other encodings; however, don’t worry, take a look below:

encodeURIComponent, which converts special characters such as Chinese and Korean into url encoding in utf-8 format.

escapeWhen encoding unicode values ​​other than 0-255, the %u**** format is output. In other cases, the encoding results of escape, encodeURI, and encodeURIComponent are the same.

Haha, do you see hope? That's right, use escape instead of the encodeURIComponent method, but you must pay attention:

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

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

After using escape, the plus sign must be encoded. Otherwise, when the content contains a plus sign, it will be translated into spaces by the server.

Finally I know the solution, rewrite the jquery code:

Copy the code The code is 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 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 a )
// 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(/ /g, " ");
}

The above code does not need to be rewritten in the jquery source file. It can be added in your project Paste javascript to overwrite its original method, but it must be after jquery is loaded.

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, which affects both the frontend and the backend. Ajax post under gbk encoding is no longer a problem, this is the ultimate solution. Ha ha.

Those who are interested can go to http://www.open-lib.com/Forum/Read_69_1.action to communicate with the author.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template