AJAX处置以XML返回的响应
AJAX处理以XML返回的响应
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(); }
相关推荐
坚持着执着 2020-06-16
wcqwcq 2020-06-14
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07