View Plaincopy to Clipboardprint?
<% @ pagelanguage="java" import="java.util.*" pageEncoding="UTF-8"%>
06, began to use Ajax technology, at that time the term has not arisen, and later heard of Ajax, only to find that the original name.
Early on, the relevant information is quite small, the Chinese problem is very headache, until now, online also do not have a good solution.
Recently, learned that some friends are deeply immersed in them, they put their former solution to get out of the sun, I hope to miss into the industry some help friends.
Principle: HTML cannot be set to encode, but XML can, we use XML, the data to carry the past, it is OK.
JS Core code:
//Note: Xmldoc,xmlhtml object creation in a more complete way, here is a simple demonstration of the
function Dosubmit () {
var Str=document.getelementbyid (" Input1 "). Value;
//Suppose Str is the data you want to submit
alert (str);
//"MSXML2. DOMDocument "," Microsoft.XMLDOM "," MSXML. " DOMDocument "," MSXML3. DOMDocument "
var xmldoc=new activexobject (" MSXML2. DOMDocument ");
//Initialize XML Document Object
Xmldoc.loadxml (" xmldoc.documentelement.text=str;// As content to carry
//If it is more convenient to carry data with attributes, you can use the following method
//xmldoc.documentelement.setattribute ("name", "MSG");
// XmlDoc.documentElement.setAttribute ("value", str);
Alert (xmldoc.xml)//view generated XML content
//"msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0" , "MSXML2. XMLHttp "," Microsoft.XMLHTTP ";
var xmlhttp=new activexobject ("msxml2.xmlhttp.5.0");
var url= "servlet/myservlet?time=" + (new Date ()). GetTime ();
Xmlhttp.open ("POST", Url,false);
Xmlhttp.send (xmldoc);//Send the XML object out
Alert (xmlhttp.responsetext);
}
Servlet/action Core Code:
// 读取ajax发送来的xml数据
SAXReader xmlReader = new SAXReader();
Document document = null;
try {
document = xmlReader.read(request.getInputStream());
} catch (Exception ex) {
System.err.println("xml读取失败,可能没有xml数据.");
ex.printStackTrace();
}
System.out.println("接收到xml数据:" + document.asXML());
// 解析xml
String str = document.getRootElement().getText();
System.out.println("解析出来的数据:" + str);
// 返回结果
response.setContentType("text/html; charset=UTF-8");// GBK也行,指明返回的编码
response.getWriter().print("服务器返回信息:成功啦!\no(∩_∩)o...哈哈!");// 返回中文也没问题啦
Key points:
JS to create XMLDOM objects, as well as the background of the parsing, the background used dom4j, to parse XML.