Home > Article > Web Front-end > What to do if jquery ajax submits garbled code
The solution to jquery ajax submission of garbled codes: 1. Unify the encoding settings; 2. Use the post method to pass parameters; 3. Escape encoding in the js front end and then decode in the background to obtain the data; 4. Globally Set the contentType and specify the encoding.
The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.
Recommended: jquery tutorial
jquery What should I do if ajax submits garbled data?
When I use jquery to process html5 applications, the test under firefox is normal. When the user accesses it with a pad, it says that there are garbled characters. I tested it myself and sure enough, and then found that under the chrome and ie kernel Everyone has this problem. When the page attribute is set to utf-8, only Firefox transmits the charset=utf-8 header file. Chrome and IE do not specify it, so garbled characters appear.
Solution:
The code is as follows:
$.ajaxSetup({ contentType: "application/x-www-form-urlencoded; charset=utf-8" }); $.post("test.php", { name: "i5a6", time: "2pm" }, function(data){ process(data); }, "json");
Or use:
The code is as follows:
$.ajax({ url:url, type:"POST", data:data, contentType:"application/x-www-form-urlencoded; charset=utf-8", dataType:"json", success: function(){ ... } })
It is recommended to use the first one, However, it is based on your actual situation. Some people recommend using encodeURIComponent for character conversion.
Summarize some experience of garbled data submitted by ajax.
In order to avoid garbled characters, you can do the following steps
Solution
1. Keep the encoding unified, including file encoding, database encoding, and web page content-type encoding
Check4e9857ad2e3c8b43d69358f441fd4d82
It is recommended to use UTF-8 for Chinese. Using gbk/gb2312 may cause garbled characters
2, use post to send instead of get
The get method will pass parameters through the link, and will automatically urlEncode (encode), and the encoding method of each browser may be different. Using post can avoid this situation.
3, by escaping the front-end encoding in js and then sending it, and then decoding it in the background to obtain the data
These can be searched online
4, set the contentType globally and specify the encoding
Because jquery ajax uses utf-8 to encode and send data, IE does not add charset=utf-8 when sending, resulting in garbled characters (IE uses iso-8859-1 encoding by default)
The code is as follows:
$.ajaxSetup({ contentType: "application/x-www-form-urlencoded; charset=utf-8" });
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of What to do if jquery ajax submits garbled code. For more information, please follow other related articles on the PHP Chinese website!