标签:des style blog http color java os 使用 io

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">      functionjj(){                  $.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 | packageservlet;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassAjaxServlet extendsHttpServlet {    publicAjaxServlet() {        super();    }    publicvoiddestroy() {        super.destroy();             }    publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)            throwsServletException, IOException {        doPost(request, response);    }    publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)            throwsServletException, IOException {        // 这里响应类型必须是text/xml        response.setContentType("text/xml;charset=gbk");         request.setCharacterEncoding("gbk");        PrintWriter out = response.getWriter();        // XML头,没有这个可能Javascript解析不出XML,最好设一下        StringBuilder sb = newStringBuilder("<?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();    }    publicvoidinit() throwsServletException {}} | 
标签:des style blog http color java os 使用 io
原文地址:http://www.cnblogs.com/liwenjie/p/3930566.html