How to deal with the Chinese garbled code when AJAX submits the data
This article introduces the relevant knowledge of "how to deal with Chinese garbled when AJAX submits data". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Principle: html can not set coding, but xml can, we use xml, take the data to the past, it is OK.
Js core code:
/ Note: please use a more perfect way to create xmlDoc,xmlHtml objects. This is just a brief demonstration.
FunctiondoSubmit () {
Varstr=document.getElementById ("input1"). Value
/ / suppose str is the data you want to submit
Alert (str)
/ / "MSXML2.DOMDocument", "Microsoft.XMLDOM", "MSXML.DOMDocument", "MSXML3.DOMDocument"
VarxmlDoc=newActiveXObject ("MSXML2.DOMDocument")
/ / initialize the xml document object
XmlDoc.loadXML ("")
XmlDoc.documentElement.text=str;// is carried as content.
/ / if it is more convenient to use attributes to carry data, you can use the following methods
/ / xmlDoc.documentElement.setAttribute ("name", "msg")
/ / xmlDoc.documentElement.setAttribute ("value", str)
Alert (xmlDoc.xml); / / View the generated xml content
/ / "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"
VarxmlHttp=newActiveXObject ("MSXML2.XMLHttp.5.0")
Varurl= "servlet/MyServlet?time=" + (newDate ()) .getTime ()
XmlHttp.open ("POST", url,false)
XmlHttp.send (xmlDoc); / / send the xml object
Alert (xmlHttp.responseText)
}
How to deal with Chinese when AJAX submits data
Servlet/action core code:
/ / read the xml data sent by ajax
SAXReaderxmlReader=newSAXReader ()
Documentdocument=null
Try {
Document=xmlReader.read (request.getInputStream ())
} catch (Exceptionex) {
System.err.println ("xml read failed, there may be no xml data")
Ex.printStackTrace ()
}
System.out.println ("received xml data:" + document.asXML ())
/ / parsing xml
Stringstr=document.getRootElement () .getText ()
System.out.println ("parsed data:" + str)
/ / return the result
Response.setContentType ("text/html;charset=UTF-8"); / / GBK is also fine, indicating the returned code
Response.getWriter (). Print ("Server returned message: successful!\ no (∩ _ ∩) o... !"); / / No problem with returning Chinese
Key points:
Create xmlDom objects in js, and parse in the background. Dom4j is used in the background to parse xml.
This is the end of the content of "how to deal with Chinese garbled when AJAX submits data". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!