How can I prevent garbled characters in the Chinese data returned by the XMLHTTPRequest object?

Source: Internet
Author: User

How can I prevent garbled characters in the Chinese data returned by the XMLHTTPRequest object?


When using Ajax for website development, we use XMLHTTPRequest object to transmit data. Because the operating system used by the user machine and the default language configuration used by the browser may be different, some users use the English configuration scheme and some users use the traditional Chinese configuration scheme. Because different encoding methods are used for the same transmitted data, some users' machines may encounter garbled characters when displaying your webpage, so how should we solve this problem?
Anyone who has experience writing HTML knows that when using an HTML webpage, we can add the following tags to the CodeTraditional Chinese, "UTF-8" represents UNICODE character encoding and so on.
In XMLHttpRequest, we can also adopt a similar method, that is, specify the character encoding of the transmitted data in the HTTP Request Header, so that the browser will no longer use its default encoding method to interpret the data, it will be interpreted based on the character set encoding specified in the HTTP header to effectively prevent garbled data.
The specific method is as follows: the XMLHTTPRequest object has a setRequestHeader ("Header", "value") method. This method has two parameters, the first parameter (header) specifies the name of the key to be added to the HTTP request header, and the second parameter (value) specifies the corresponding value of this key. If the object transmitted using XMLHttpRequest is simplified Chinese data, you can use the following command to declare setRequestHeader ("Content-Type", "gb2312") in the HTTP Request Header, so that the browser can interpret the transmitted data with the correct character set to prevent garbled characters.

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.