jQuery Ajax访问XML数据及Java后端生成示例

作者:工具松鼠

时间:2026-10-27

浏览:177

本文介绍如何使用jQuery的Ajax方法以POST方式请求XML数据,并在Java后端通过ActionMapping和Response对象生成XML响应。前端通过success回调解析XML节点属性,后端设置正确的Content-Type和字符编码,确保数据交互正常。

文章目录

前端jQuery Ajax请求XML数据

前端JavaScript代码实现

具体实现代码如下:

$.ajax({
url : '...',
type : 'POST',
datatype : 'xml',
error : function(xml) {
alert("Error loading XML document" + xml);
},
success : function(xml) {
$(xml).find("X").each(function(i) {
alert($(this).attr("Xattr"));
});
}
});

后端Java生成XML响应

后端Java代码实现


具体实现代码如下:

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/xml; charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter pw = response.getWriter();
Document doc = new Document();//获取XML文件
doc.write(pw);
return null;
}

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章