Ajax请求,服务器端返回XML形式的数据,在页面上用Javascript处理会非常方便。
代码:
// 发送请求 var req; function getXMLHttpRequest() { var xRequest = null; if (window.XMLHttpRequest) { xRequest = new XMLHttpRequest(); } else if (typeof ActiveXObject != "undefined") { xRequest = new ActiveXObject("Microsoft.XMLHTTP"); } return xRequest; } function sendRequest(url,params,HttpMethod,callback) { if (!HttpMethod) { HttpMethod = "GET"; } req = getXMLHttpRequest(); if (req) { req.onreadystatechange = callback; req.open(HttpMethod,url,true); req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=EUC-JP"); req.send(params); } }
// 回调函数 function change() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { var data = xmlHttp.responseXML; var datas = data.getElementsByTagName('info'); for (var i = 0; i < datas.length; i++) alert(datas[i].firstChild.nodeValue); datas = data.getElementsByTagName('memo'); for (i = 0; i < datas.length; i++) alert(datas[i].firstChild.nodeValue); } } }
// 服务器端代码 // XML头,没有这个Javascript解析不出XML,编码一定要设,要不然会乱码 StringBuilder infoBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"EUC-JP\"?>"); // 根元素<root></root>一定需要,否则Javascript解析不出XML,但名字不一定要叫root infoBuilder.append(("<root><info>a</info><info>b</info><memo>c</memo><memo>d</memo></root>"); ); PrintWriter writer = null; try { // 设置编码 response.setContentType("text/xml;charset=EUC-JP"); writer = response.getWriter(); writer.println(infoBuilder.toString()); writer.flush(); } catch (Exception e) { } finally { if (writer != null) writer.close(); }