search
HomeWeb Front-endJS TutorialPerfectly solve the problem of Chinese characters displaying garbled characters in JS (solved)_Basic knowledge

As mentioned, I just read a few discussions and suddenly thought of posting the issues I have been researching recently. All issues related to garbled characters in JS are posted here so that we can study them together. . :)
Scenario 1: The content written by write is in UTF-8 format. If the saved write data contains Chinese that is not UTF-8 encoded, nesting the write more than twice will cause garbled characters. Since there is no ready-made file at hand, I just made a temporary one. This is the code of the 1.htm page:

The code is as follows:

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">  
<script language="JavaScript" src="1.js"></script>  
</head>  
<body onload=myjs(1)>  
</body>  
</html>

This is the quote’s 1.js file code, both files are saved in simplified Chinese instead of utf-8

The code is as follows:

//这是JS
递归
自写过程中汉字乱码的演示程序  
//不光是中文内容不行,就连
注释
如果是中文有时候也不行  
//感觉JS一碰上中文就变得很不稳定=_=&#39;  
//Dec. 29th 2005 created by shouhaimu(QQ:30836570)  
function myjs(i)  
{  
    var t="<html>\n";  
    t+="<head>\n";  
    t+="<meta http-equiv=&#39;Content-Type&#39; content=&#39;text/html; charset=gb2312&#39;>\n";  
    t+="<script language=&#39;JavaScript&#39; src=&#39;1.js&#39;></script>\n";  
    t+="</head>\n";  
    t+="<body>\n";  
    t+="<input type=button 
onclick
=myjs("+(i+1)+" value=&#39;这是演示程序,已经运行了"+i+"次!&#39;>\n";  
//上面这行如果改成下面这句就可以正常显示,看来确实是JS对汉字的支持不够好:  
//t+="<input type=button onclick=myjs("+(i+1)+" value=&#39;This is my code,it has run "+i+" 
time
s!&#39;>\n";  
    t+="</body>\n";  
    t+="</html>\n";  
    
document
.open();  
    document.write(t);  
    document.close();  
}

It will run for the second time or more There are garbled characters.
Scenario 2: When a file is obtained through XMLHTTP and then output, if the file contains Chinese information and is encoded by gb, the Chinese information will be garbled when displayed.
The js code is as follows: (comments were added when posting, you can remove them if you are afraid of interference)

The code is as follows:

<SCRIPT language="JavaScript" type="text/JavaScript">  
self.onerror=
null
;  
var Http = 
new
 ActiveX
Object
("Microsoft.XMLHTTP";  
Http.open("GET",URL,false);      //URL是您需要获取的页面的网址  
Http.s
end
();  
document.write(Http.responseText);  
</SCRIPT>  
后来用VBS解决,改成如下:  
<SCRIPT language="
VBScript
" type="text/VBScript">  
Function bytes2BSTR(vIn)  
str
Return
 = ""  
For
 i = 1 To LenB(vIn)  
ThisCharCode = AscB(MidB(vIn,i,1))  
If
 ThisCharCode < &H80 Then  
strReturn = strReturn & 
Chr
(ThisCharCode)  
Else
  
Next
CharCode = AscB(MidB(vIn,i+1,1))  
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))  
i = i + 1  
End If  
Next  
bytes2BSTR = strReturn  
End Function  
set Http = CreateObject("Microsoft.XMLHTTP"  
Http.open "Get",URL,false   //URL是您需要获取的页面的网址  
Http.send ""  
document.write(bytes2BSTR(Http.responseBody))  
</SCRIPT>

Note: The above bytes2BSTR only The responseBody can be operated, but the responseText operation cannot be displayed normally, because the responseText is processed by the system according to the default encoding. It is a bunch of garbled code and cannot be processed. But this way I can read Simplified Chinese files, but there will be errors when reading UTF-8.
Discussion on issues related to garbled Chinese characters when JS is running (please refer to other special posts for problems that arise during editing)

I have heard about some of them and done tests. There are still three key mysteries that have not been solved. :

1. Even if the page was displayed normally, it will no longer be displayed normally if you use back or read a non-utf-8 page;

2. Even if all the protection measures are taken, All measures for garbled characters (except for re-encoding, of course) have been adopted, and even if you use the same program to open a page, there is no guarantee that the page will be stably displayed in Chinese every time;

3. Remote acquisition of data submission The problem with the form is that if the target website uses encoding and decoding, it means that if the display is normal, the submitted content will become garbled, and vice versa. So I had to re-encode all the obtained content in advance, so I couldn't do without the encoding program, and I couldn't get rid of the shadow of VBS =_='

I also found a problem in the test just now
Posted previously VBS re-encoding function , if the page is too large, IE will hang. The specific size is estimated to be related to the cache and memory size. In short, if I were to rank the degree of Chinese support, JSASPstatic. Of course, they are the most stable, so make dynamic pages. If not It must be run on the client, and it is strongly recommended to use ASP to generate code.

The above is the perfect solution to the problem of garbled Chinese character display in JS (solved)_basic knowledge. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor