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.