JavaWeb——Ajax

本文详细介绍了AJAX的局部刷新原理,展示了XMLHttpRequest的核心作用,并探讨了如何结合JSON进行数据交换,包括使用Jackson将Java对象转为JSON格式。实例演示了根据省份ID查询数据库并显示结果的过程。
摘要由CSDN通过智能技术生成

Ajax

1. 全局刷新和局部刷新

全局刷新和局部刷新图解

全局刷新:整个浏览器被新的数据覆盖。但由于在网络中要传输大量的数据,浏览器需要加载,渲染页面,往往给用户的感受不是很好。

局部刷新:在浏览器的内部,发起请求,获取数据,改变页面中的部分内容。其余的页面无需加载和渲染。网络中数据传输量少,给用户的感受好。

ajax就是用来作局部刷新的。局部刷新使用的核心对象是异步对象(XMLHttpRequest)

这个异步对象是存在浏览器内存中的,使用JavaScript语法创建和使用XMLHttpRequest对象。

2. 什么是AJAX

ajax:Asynchronous JavaScript and XML (异步的JavaScript 和 XML)。

  • Asynchronous:异步的
  • JavaScript:javascript脚本,在浏览器中执行
  • and:和
  • XML:一种数据格式

ajax是一种作局部刷新的新方法,不是一种语言。ajax包含的技术主要有JavaScript、dom、css、xml等。

其中核心是JavaScriptxml

  • JavaScript:负责创建异步对象,发送请求,更新页面的dom对象。ajax请求需要服务器端的数据。

  • xml:网络中传输的数据格式。

    <数据>
    	<数据1> 宝马1 </数据1>
    	<数据2> 宝马2 </数据2>
    	<数据3> 宝马3 </数据3>
    </数据>
    

    但由于它数据较长、冗余又比较啰嗦,在传输过程花的时间和空间都不小,逐渐被json所替代了。

3. ajax中使用XMLHttpRequest对象

  1. 创建异步对象var xmlHttp = new XMLHttpRequest();

  2. 给异步对象绑定事件onreadystatechange。当异步对象发起请求,获取了数据都会触发这个事件。这个事件需要指定一个函数,在函数中处理状态的变化。

    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
            // 可以处理服务器端的数据,更新当前页面
            var data = xmlHttp.responseText;
            document.getElementById("name").value=data;
        }
    }
    

    异步对象的属性readystate表示异步对象请求的状态变化

    0:创建异步对象时,new XMLHttpRequest();

    1:初始异步请求对象,xmlHttp.open( 请求方式,请求地址,true )

    2:发送请求,xmlHttp.send()

    3:异步对象接收应答数据 从服务端返回数据。XMLHttpRequest 内部处理。 (一般不用,是原始数据)

    4: 异步请求对象已经将数据解析完毕。 此时才可以读取数据。

    异步对象的属性status属性,表示网络请求的状况的(200、404、500…),需要是当status==200时,表示网络请求是成功的。

  3. 初始异步请求对象
    使用异步的方法open()
    格式:xmlHttp.open(请求方式get|post, "服务器端的访问地址", 同步|异步请求(默认是true,即异步请求));
    例如:xmlHttp.open("get", "loginServlet?name=zs&pwd=123", true);

  4. 使用异步对象发送请求xmlHttp.send()

获取服务器端返回的数据,使用异步对象的属性responseText:xmlHttp.responseText

回调:当请求状态变化时,异步对象会自动调用onreadystatechange事件对应的函数。

例子:根据用户传入的省份id到数据库中去查询对应的省份名称

  • 数据库表:

数据库表

  • index.jsp:接收用户输入的数据并交给服务器,然后获取服务器查询的结果并展示。

    <html>
      <head>
        <title>$Title$</title>
        <script type="text/javascript">
          function search() {
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function () {
              if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
                document.getElementById("proname").value = xmlHttp.responseText;
              }
            }
            var proid = document.getElementById("proid").value;
            xmlHttp.open("get", "/myWeb/queryProvince?proid="+proid, true);
            xmlHttp.send();
          }
        </script>
      </head>
      <body>
      <p>ajax根据省份id获取名称</p>
      <table border="3">
        <tr>
          <td>省份编号:</td>
          <td>
            <input type="text" id="proid">
            <input type="button" value="搜索" onclick="search()">
          </td>
        </tr>
        <tr>
          <td>省份名称:</td>
          <td><input type="text" id="proname" readonly></td>
        </tr>
    
      </table>
      </body>
    </html>
    
  • queryProvinceServlet:

    public class queryProvinceServlet extends HttpServlet {
    
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            String proid = request.getParameter("proid");
            String name = "默认是无数据";
            if (proid != null && !"".equals(proid.trim())){
                ProvinceDao dao = new ProvinceDao();
                try {
                    name = dao.queryProvinceNameById(Integer.valueOf(proid));
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
    
            // 使用HttpServletResponse输出数据
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(name);
            out.flush();
            out.close();
        }
    }
    
  • provinceDao:进行数据库操作

    public class ProvinceDao {
    
        // 根据id获取名称
        public String queryProvinceNameById(Integer proviceId) throws SQLException {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            String sql = "";
            String url = "jdbc:mysql://localhost:3306/springdb?serverTimezone=UTC";
            String username = "root";
            String password = "549436";
            String name = "";
            // 加载驱动
            try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(url, username, password);
                sql = "select name from province where id=?";
                ps = conn.prepareStatement(sql);
                ps.setInt(1, proviceId);
                rs = ps.executeQuery();
                while(rs.next()){
                    name = rs.getString("name");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (rs != null){
                        rs.close();
                    }
                    if (ps != null){
                        ps.close();
                    }
                    if (conn != null){
                        conn.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return name;
        }
    }
    
  • 运行结果:

未输入前
输入后

4. 引入json

json详细介绍(这个里面用到的json工具库是json-lib)

json分类

  1. json对象,JSONObject。
  2. json数组,JSONArray。

使用json原因

  1. json格式好理解
  2. json格式在多种语言中,比较容易处理
  3. json格式数据占用空间小,在网络中传输快,用户体验好

处理json的工具库:gson(google)、fastjson(阿里)、jackson、json-lib

下面我们要使用jackson工具处理json

不过在使用前我们还需要导入三个jar包:

需要导入的jar包

例子:使用jackson把Java对象转为json格式字符串(学习使用jackson)

  • 实体类Province:

    public class Province {
        private  Integer id;
        private String name;
        private String jiancheng;
        private String shenghui;
    
        public Province() {
        }
    
        public Province(Integer id, String name, String jiancheng, String shenghui) {
            this.id = id;
            this.name = name;
            this.jiancheng = jiancheng;
            this.shenghui = shenghui;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getJiancheng() {
            return jiancheng;
        }
    
        public void setJiancheng(String jiancheng) {
            this.jiancheng = jiancheng;
        }
    
        public String getShenghui() {
            return shenghui;
        }
    
        public void setShenghui(String shenghui) {
            this.shenghui = shenghui;
        }
    }
    
  • Test.java:用来测试

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.moyan.entity.Province;
    
    public class Test {
        public static void main(String[] args) throws JsonProcessingException {
            Province p = new Province(1, "河北", "冀", "石家庄");
    
            // 使用jackson把p转为json
            ObjectMapper om = new ObjectMapper();
            // writeValueAsString:把参数的Java对象转为json格式的字符串
            String json = om.writeValueAsString(p);
            System.out.println("转换的json == " + json);
        }
    }
    
    
    
    输出:转换的json == {"id":1,"name":"河北","jiancheng":"冀","shenghui":"石家庄"}
    

5. 完整的使用json作为数据交换的格式的例子

输入省份编号,从数据库中查询出该省份编号对应的省份名称、省份简称、省会名称。服务端将这些数据以JSON字串形式返回,前端从得到的json中取出数据并展示。

数据库表

数据库表

各文件

  • myajax.jsp:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>使用json格式数据</title>
        <script type="text/javascript">
            function doSearch() {
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.onreadystatechange = function () {
                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
                        var data = xmlHttp.responseText;
                        var res = eval("("+data+")"); // eval是执行括号中代码,把json字符串转为json对象
                        document.getElementById("proname").value = res.name;
                        document.getElementById("projiancheng").value = res.jiancheng;
                        document.getElementById("proshenghui").value = res.shenghui;
                    }
                }
                var proid = document.getElementById("proid").value;
                xmlHttp.open("get", "/myWeb/queryJson?proId="+proid, true);
                xmlHttp.send();
            }
        </script>
    </head>
    <body>
        <p>ajax请求使用json格式的数据</p>
        <table>
            <tr>
                <td>省份编号:</td>
                <td>
                    <input type="text" id="proid">
                    <input type="button" value="搜索" onclick="doSearch()">
                </td>
            </tr>
            <tr>
                <td>省份名称:</td>
                <td><input type="text" id="proname" readonly></td>
            </tr>
            <tr>
                <td>省份简称:</td>
                <td><input type="text" id="projiancheng" readonly></td>
            </tr>
            <tr>
                <td>省会名称:</td>
                <td><input type="text" id="proshenghui" readonly></td>
            </tr>
        </table>
    </body>
    </html>
    

    前端界面

  • Province.java

    public class Province {
        private  Integer id;
        private String name;
        private String jiancheng;
        private String shenghui;
    
        public Province() {
        }
    
        public Province(Integer id, String name, String jiancheng, String shenghui) {
            this.id = id;
            this.name = name;
            this.jiancheng = jiancheng;
            this.shenghui = shenghui;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getJiancheng() {
            return jiancheng;
        }
    
        public void setJiancheng(String jiancheng) {
            this.jiancheng = jiancheng;
        }
    
        public String getShenghui() {
            return shenghui;
        }
    
        public void setShenghui(String shenghui) {
            this.shenghui = shenghui;
        }
    }
    
  • QueryJsonServlet.java

    public class QueryJsonServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String proId = request.getParameter("proId");
            Province province = null;
            if (proId != null && !"".equals(proId.trim())){
                ProvinceDao dao = new ProvinceDao();
                province = dao.queryProvinceById(Integer.valueOf(proId));
            }
            ObjectMapper om = new ObjectMapper();
            String msg = om.writeValueAsString(province);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(msg);
            out.flush();
            out.close();
        }
    }
    
  • ProvinceDao.java

    public class ProvinceDao {
    
        public Province queryProvinceById(Integer proId){
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            String sql = "";
            String url = "jdbc:mysql://localhost:3306/springdb?serverTimezone=UTC";
            String username = "root";
            String password = "549436";
            Province province = null;
            // 加载驱动
            try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(url, username, password);
                sql = "select * from province where id=?";
                ps = conn.prepareStatement(sql);
                ps.setInt(1, proId);
                rs = ps.executeQuery();
                if(rs.next()){
                    province = new Province();
                    province.setId(rs.getInt("id"));
                    province.setJiancheng(rs.getString("jiancheng"));
                    province.setShenghui(rs.getString("shenghui"));
                    province.setName(rs.getString("name"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (rs != null){
                        rs.close();
                    }
                    if (ps != null){
                        ps.close();
                    }
                    if (conn != null){
                        conn.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return province;
        }
    }
    

运行结果

运行结果

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小陌白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值