Home > Web Front-end > JS Tutorial > body text

jquery ajax post submission data is garbled_jquery

WBOY
Release: 2016-05-16 17:17:21
Original
931 people have browsed it

When using jquery to process html5 applications, the test under firefox was normal. When the user accessed it with a pad, it said that there were garbled characters.
I tested it myself and sure enough, I found that this problem exists under the chrome and ie kernels. For this problem, when the page attribute is set to utf-8, only Firefox passes the charset=utf-8 header file
Chrome and IE are not specified, so garbled characters appear.
Solution:

Copy code 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:
Copy code 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, but it is also based on your actual situation. Some people recommend using encodeURIComponent for character conversion
Summarize some experience of ajax submitting garbled data
In order to avoid garbled codes, you can do the following steps
Solution
1. Keep the encoding unified, including file encoding, database encoding, and web page content-type encoding
Check
It is recommended to use UTF-8 for Chinese. Using gbk/gb2312 may cause garbled characters
2. Use post to send Instead of get
get method will pass the 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. Escape encoding in the js front-end and then send it, and then decode 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 is used to encode the sent data, but IE does not add charset=utf-8 when sending, resulting in garbled characters (IE uses iso-8859-1 encoding by default)
Copy the code The code is as follows:

$.ajaxSetup({
contentType: "application/x-www-form-urlencoded; charset=utf-8"
});
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