If Chinese is submitted using a form, garbled characters will not appear, but if submitted using ajax, garbled characters will appear. What is the reason for this?
My understanding is that when I write source code, I usually use Notepad to write it. When saving, I use ANSI encoding by default. There is no "" or "header('Content-Type:text/html;charset=UTF-8');" specifies the web page encoding, so When displayed in the browser, its encoding is identified as "GB2312". When the frontend transmits data to the backend, if you use a form to submit, the frontend and backend will use "GB2312" encoding to communicate, and there will be no garbled characters; if you use ajax to submit, ajax will convert the data encoding to be sent from "GB2312" in the frontend. into "UTF-8" and then pass it to the backend, and then treat the received data returned by the backend as "UTF-8" and convert it into "GB2312" before displaying it on the frontend page. In this way, garbled characters are generated.
As shown in the picture:
So to solve the garbled code, the data encoding conversion needs to be performed in the background. The data received in the background uses PHP's mb_convert_encoding("data to be converted","gb2312 ","UTF-8") is converted and stored in the database. The Chinese data returned from the background to the front desk must also be converted using mb_convert_encoding("data to be returned", "UTF-8", "gb2312") and returned.