客户端js:
<script type="text/javascript">
function testBack(){ //创建对象 var req; if(window.XMLHTTPRequest){ req = new XMLHttpRequest(); }else if(window.ActiveXObject){ req = new ActiveXObject("Msxml2.XMLHTTP"); } //创建请求 请求方式 请求路径 同步/异步 req.open("post","HelloBack",true); //监听响应信息 req.onreadystatechange = function(){ if(req.readyState==4){ if(req.status==200){ //var result = req.responseText; //eval("var user = "+result); //alert(user.uname); //eval("var users = "+result); //alert(users[2].realname); var result = req.responseXML; alert(result.getElementsByTagName("uname")[0].firstChild.data); } } } //发送请求 req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); req.send(null); } </script>servlet:
public class HelloBack extends HttpServlet {
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); //第一种普通文本 //resp.setContentType("text/html;charset=utf-8"); //resp.getWriter().print("普通文本"); //Json格式数据 //resp.setContentType("text/html;charset=utf-8"); //resp.getWriter().print("[{uname:'zhangsan',realname:'张三三1'},{uname:'zhangsan',realname:'张三三2'},{uname:'zhangsan',realname:'张三三3'}]"); //XML格式的数据 返回数据的格式必须要正确 resp.setContentType("text/xml;charset=utf-8"); resp.getWriter().print("<user><uname>zhangsan</uname></user>"); } }