ajax技术

上面是index.jsp页面,如果要使用标签那么就要导入jstl的包,然后采用绝对路径来访问其他的界面。

 

下面是ajaxXml.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>ajax处理xml数据演示示例</title>
        <script type="text/javascript">
            function send1(){
                alert("返回的信息是:");
                var name = document.getElementById("nm").value;
                
                //1创建ajax对象
                var xhr=null;
                if(window.XMLHttpRequest){//高版本IE,火狐等
                    xhr = new XMLHttpRequest();
                }else{//低版本IE
                    xhr = new ActiveXObject("Microft.XMLHttp");
                }
                
                //2请求地址
                var url = "<c:url value='/XmlServlet?name="+name+"'/>"; //get方式,请求参数在地址栏中
                
                //3设置访问方式
                xhr.open("GET", url, true);
                
                //4设置访问成功返回后的操作
                xhr.onreadystatechange = function(){
                    if(xhr.readyState==4){
                        if(xhr.status==200){
                            var txt = xhr.responseText;
                            alert("返回的信息是:"+txt);
                        }
                    }
                };
                //5发送
                xhr.send(null);
                
            }
            
            function send2(){
                
                //1创建ajax对象
                var xhr=null;
                if(window.XMLHttpRequest){//高版本IE,火狐等
                    xhr = new XMLHttpRequest();
                }else{//低版本IE
                    xhr = new ActiveXObject("Microft.XMLHttp");
                }
                //2请求地址
                var url = "<c:url value='/XmlServlet'/>"; //post方式,请求参数在 send()方法的实参
                //3设置访问方式
                xhr.open("POST", url, true);
                //4设置访问成功返回后的操作
                xhr.onreadystatechange = function(){
                    if(xhr.readyState==4){
                        if(xhr.status==200){
                            //接收后台发过来的xml格式文档(字符串)
                            var xmlDomObj = xhr.responseXML;//★★★这种方式接收到的是一个 XmlDomObject
                            //alert(xmlDomObj); //object
                            //从XmlDom对象中解析出数据
                            var users = xmlDomObj.getElementsByTagName("user");//array
                            for(var i=0; i<users.length; i++){
                                var id = users[i].getAttribute("id");
                                var name = users[i].childNodes[0].firstChild.data;
                                var age = users[i].childNodes[1].firstChild.data;
                                alert(id+", "+name+", "+age);//这个地方的数据是通过获取后台数据进行显示 的;
                            }
                        }
                    }
                };
                
                ///////////////////////1111/////////////////////////
                //向后台发送XML格式的字符串
                var name = document.getElementById("nm").value;
                var age = document.getElementById("ag").value;
                var xml ="<user><name>"+name+"</name><age>"+age+"</age></user>";
                
                xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded" );
                //5发送
                xhr.send(xml);
                
            }
        </script>
    </head>
    <body>
        Name:<input type="text" id="nm" name="name" /><br/>
        Age:<input type="text" id="ag" name="age" /> <br/>
        <!-- send1()和XmlServlet的doGet()不是我们今天的新知识,只是复习,便于我们过渡到新知识点 -->
        <input type="button" onclick="send1();" value="get发送ajax"><br/><br/>
        
        <input type="button" onclick="send2();" value="post-ajax发送XML数据">
    </body>
</html>




下面是servlet层,下面是XmlServlet.servlet
package
cn.hncu.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.hncu.domain.User;

@WebServlet("/XmlServlet")
public class XmlServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get....");
        String name = request.getParameter("name");
//        name = new String(name.getBytes("ISO8859-1"),"utf-8");
//        System.out.println("name:"+name);
//        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("XmlServlet Answer 1223: "+name);
    }
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        InputStream in = request.getInputStream();
        BufferedReader br = new BufferedReader( new InputStreamReader(in));
        String line = null;
        String xml="";
        while((line=br.readLine())!=null){
            xml = xml + line;
        }
        System.out.println(xml);
        //上面只是把前端发过来的 符合xml格式的字符串(文档)读取出来
        
        //下面用dom4j来解析出 xml格式的文档
        SAXReader sax = new SAXReader();
        
        try {
            Document dom = sax.read( new StringReader( xml ) );
            Element root = dom.getRootElement();
            String name = root.elementText("name");
            String age = root.elementText("age");
            System.out.println("后台解析xml文档的结果:"+name+","+age);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        
        ////////////////////////222/////////////////////////
        ////以下演示后台向前端发送xml格式的数据
        //按理应该调用service、dao层并从数据库中把数据读取出来,这里模拟了...
        List<User> users = new ArrayList<User>();
        users.add( new User("U001","Jack",22));
        users.add( new User("U010","张三",12));
        users.add( new User("U002","Rose",23));
        //<users> <user id="U001"><name>Jack</name><age>22</age> </user> <user id="U010"><name>张三</name><age>12</age></user> ... </users>
        String res = "<users>";
        for(User u:users){
            res += "<user id=\""+u.getId()+"\"><name>"+u.getName()+"</name><age>"+u.getAge()+"</age></user>"; 
        }
        res +="</users>";
        
        //发给前端
        response.setContentType("text/xml;charset=utf-8");//★★★
        response.getWriter().print(res);
    }

}

 

//发给前端
response.setContentType("text/xml;charset=utf-8");//★★★
response.getWriter().print(res);

//在前端页面获取后台发过来的信息

var xmlDomObj = xhr.responseXML;//★★★这种方式接收到的是一个 XmlDomObject
//alert(xmlDomObj); //object
//从XmlDom对象中解析出数据
var users = xmlDomObj.getElementsByTagName("user");//array

 



 

posted @ 2017-03-06 17:03  折腾青春  阅读(278)  评论(0编辑  收藏  举报