客户端:
<script type="text/javascript">
function getXml(){
var name = $("#input").val();
alert("into getXml()");
$.ajax({
type : "post",
url : "/ajaxReturnXmlServlet",
dataType : "XML",
data : {"name" : name},
error : function(){
alert("there is a error!");
},
success:function(xml){
$(xml).find("result").each(function(){
var name = "";
var age = "";
name = $(this).find("name").text();
age = $(this).find("age").text();
$("#member").append($("<tr><td>"+name
+"</td><td>" + age +"</td></tr>"));
}
);
}
});
}
</script>
服务器端:
public class AjaxReturnXmlServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name") == null ? "" : request.getParameter("name");
System.out.println(name);
response.setContentType("text/xml;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
StringBuffer returnXmlBuff = new StringBuffer();
returnXmlBuff.append("<?xml version="1.0" encoding="utf-8"?><root>");
returnXmlBuff.append("<result id="one">");
returnXmlBuff.append("<name>b</name>");
returnXmlBuff.append("<age>11</age></result>");
returnXmlBuff.append("<result id="two">");
returnXmlBuff.append("<name>bb</name>");
returnXmlBuff.append("<age>22</age></result>");
returnXmlBuff.append("<result id="three">");
returnXmlBuff.append("<name>cc</name>");
returnXmlBuff.append("<age>33</age></result>");
returnXmlBuff.append("<result id="fore">");
returnXmlBuff.append("<name>dd</name>");
returnXmlBuff.append("<age>44</age></result>");
returnXmlBuff.append("</root>");
System.out.println(returnXmlBuff.toString());
out.print(returnXmlBuff.toString());
out.flush();
out.close();
}
}
1、继承HttpServlet,需要添加servlet.jar包
2、serialVersionUID默认是1L,实现反序列化
3、在server.xml中,如果path="/"访问项目需要添加端口号和项目名,则页面中引用的jQuery的js引用不到,所以要使用不加项目名的访问方式
4、在Java代码的双引号里(""),如果字符串中需要有双引号这个字符,则在每一个"的前面,添加‘’来转意
5、xml格式要拼接正确
web.xml:
<servlet>
<servlet-name>AjaxReturnXmlServlet</servlet-name>
<servlet-class>com.oct.servlet.AjaxReturnXmlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxReturnXmlServlet</servlet-name>
<url-pattern>/ajaxReturnXmlServlet</url-pattern>
</servlet-mapping>