
JS代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript"> function jj(){ $.ajax({ url: ‘AjaxServlet‘, //提交的地址 type: ‘post‘, //提交方式 dataType: ‘XML‘, //数据的类型,XML、text,注意XML是大写的 error: function(){ //出现异常时调用回调函数 alert(‘无法返回正确的数据‘); }, //当成功返回数据时进行的操作, //如果前面dataType设置了XML,那么参数xml是XML文档的内容 //如果前面dataType设置了text,那么参数xml是字符串 success: function(xml){ //解析XML跟解析HTML差不多,获取文本值时最好用text(),因为有些jquery版本不支持html()解析XML alert($("b",xml).text()); $("info",xml).each(function(){ alert($(this).text()); }); } }); } </script> </head> <body> <div> <input type="button" value="点击进入ajax" onclick="jj();"/> </div> </body></html> |
Servlet代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class AjaxServlet extends HttpServlet { public AjaxServlet() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 这里响应类型必须是text/xml response.setContentType("text/xml;charset=gbk"); request.setCharacterEncoding("gbk"); PrintWriter out = response.getWriter(); // XML头,没有这个可能Javascript解析不出XML,最好设一下 StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"gbk\"?>"); // 根元素<root></root>一定需要,否则Javascript解析不出XML,但名字不一定要叫root sb.append("<root><info id=‘1‘><b>a</b></info ><info id=‘1‘>b</info><memo id=‘2‘>c</memo><memo>d</memo></root>"); //写出XML out.println(sb.toString()); out.flush(); out.close(); } public void init() throws ServletException {}} |
原文:http://www.cnblogs.com/liwenjie/p/3930566.html