Ajax

Ajax 技术简介

背景分析?

在互联网高速发展的今天,传统的WEB应用,对于高并发、高性能、高可靠性的要求已迫在眉睫。单线程方式的客户端与服务端交互方式已经不能满足现阶段的需求.我们需要以异步、按需加载的方式从服务端获取数据并及时刷新,来提高用户体验,于是Ajax技术诞生。

Ajax 是什么?

Ajax (Asynchronous JavaScript and XML) 是一种Web应用客户端技术,可以借助客户端脚本(javascript)与服务端应用进行异步通讯(可以有多个线程同时与服务器交互),并且按需获取服务端数据以后,可以进行局部刷新,进而提高数据的响应和渲染速度。

Ajax 应用场景?

Ajax技术最大的优势就是底层异步,然后局部刷新,进而提高用户体验,这种技术现在在很多项目中都有很好的应用,例如:

  • 商品系统。
  • 评价系统。
  • 地图系统。

Ajax 编程步骤及模板代码分析

Ajax 编码的基本步骤?(重点是ajax技术的入口-XMLHttpRequest-XHR对象)

第一步:基于dom事件创建XHR对象
第二步:在XHR对象上注册状态监听(监听客户端与服务端的通讯过程)
第三步:与服务端建立连接(指定请求方式,请求url,同步还是异步)
第四步:发送请求(将请求数据传递服务端)

 

Ajax 编码过程的模板代码如下:

var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
    if(xhr.readyState==4&&xhr.status==200){
           console.log(xhr.responseText)
    }
}
xhr.open("GET",url,true);
xhr.send(null);

 

SpringBoot 项目Ajax技术入门实现

第二步:添加Spring web依赖,代码如下:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

第三步:创建AjaxController处理客户端请求,代码如下:

package com.cy.pj.ajax.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AjaxController {
    @RequestMapping("/doAjaxStart")
    public String doAjaxStart(){
        return "Response Result Of Ajax Get Request 01 ";
    }
}

第四步:在项目中static目录下,创建一个页面ajax-01.html,代码如下:

html元素代码如下:

<h1>The Ajax 01 Page</h1>
<fieldset>
   <legend>Ajax 异步Get请求</legend>
   <button onclick="doAjaxStart()">Ajax Get Request</button>
   <span id="result">Data is Loading ...</span>
</fieldset>

javascript 脚本代码如下:

function doAjaxStart(){
 //debugger//客户端断点(此断点生效需要打开控制台)
 //1.创建XHR对象(XmlHttpRequest)-Ajax应用的入口对象
 let xhr=new XMLHttpRequest();
 //2.在XHR对象上注册状态监听(拿到服务端响应结果以后更新到页面result位置)
 xhr.onreadystatechange=function(){//事件处理函数(客户端与服务端通讯状态发生变化  时会执行此函数)
 //readyState==4表示服务端响应到客户端数据已经接收完成.
 if(xhr.readyState==4){
            if(xhr.status==200){//status==200表示请求处理过程没问题
               document.getElementById("result").innerHTML=
                    xhr.responseText;
            }
        }
 }
 //3.与服务端建立连接(指定请求方式,请求url,异步)
 xhr.open("GET","http://localhost/doAjaxStart",true);//true代表异步
 //4.向服务端发送请求
 xhr.send(null);//get请求send方法内部不传数据或者写一个null
//假如是异步客户端执行完send会继续向下执行.
}

服务端关键代码设计及实现

基于业务描述,在AjaxController类中添加相关属性和方法,用于处理客户端的ajax请求.

添加属性和构造方法,代码如下:

/**假设这个是用于存储数据的数据库*/
    private List<Map<String,Object>> dbList=new ArrayList<>();
    public AjaxController(){
        Map<String,Object> map=new HashMap<>();
        map.put("id","100");
        map.put("name","家用电器");
        map.put("parentId",null);//parentId为null则表示它是1级分类
        map.put("remark","电器相关等");
        map.put("createdTime",new Date());
        dbList.add(map);
    }

添加Ajax请求处理方法,代码如下:

    @GetMapping("/doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        return dbList;
    }
    @PostMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        map.put("createdTime",new Date());
        dbList.add(map);
        return "save ok";
    }
    @DeleteMapping("/doAjaxDelete")
    public String doAjaxDelete(String id){
        //获取迭代器对象,然后迭代list集合,找到id对应的元素,进行删除操作
        Iterator it=dbList.iterator();
        while(it.hasNext()){
            Map<String,Object> map=(Map<String,Object>)it.next();
            if(map.get("id").equals(id)){
                //dbList.remove(map);//这样删除会出现并发删除异常
                it.remove();//通过迭代器执行删除操作
            }
        }
        return "delete ok";
    }
    
    @PutMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> updateMap){
        Iterator it=dbList.iterator();
        while(it.hasNext()){
            Map<String,Object> map=(Map<String,Object>)it.next();
            if(map.get("id").equals(updateMap.get("id"))){
               map.put("name",updateMap.get("name"));
               map.put("remark",updateMap.get("remark"));
            }
        }
       return "update ok";
    }

客户端关键代码设计及实现

在static目录下创建ajax-02.html文件,关键代码如下:

<h1>The Ajax 02 Page</h1>
<button onclick="doAjaxGet()">Do Ajax Get</button>
<button onclick="doAjaxPost()">Do Ajax Post</button>
<button onclick="doAjaxDelete()">Do Ajax Delete</button>
<button onclick="doAjaxUpdate()">Do Ajax Update</button>
<div id="result"></div>

客户端JavaScript脚本设计,代码如下:

  • Get 请求方式,代码如下:
 function doAjaxGet(){
       let xhr=new XMLHttpRequest();
       xhr.onreadystatechange=function(){
           if(xhr.readyState==4){
               if(xhr.status==200){
                  document.getElementById("result").innerHTML=xhr.responseText;
               }
           }
       }
       xhr.open("GET","http://localhost/doAjaxGet",true);
       xhr.send(null);
    }
  • Post 请求方式,代码如下:
function doAjaxPost(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.open("POST","http://localhost/doAjaxPost",true);
        //post请求向服务端传递数据,需要设置请求头,必须在open之后
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //发送请求(post请求传递数据,需要将数据写入到send方法内部)
        xhr.send("id=101&name=Computer&remark=Computer...");
    }
  • Update 请求方式,代码如下:
 function doAjaxUpdate(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.open("put","http://localhost/doAjaxUpdate",true);
        //post请求向服务端传递数据,需要设置请求头,必须在open之后
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //发送请求(post请求传递数据,需要将数据写入到send方法内部)
        xhr.send("id=101&name=Book&remark=Book...");
    }
  • Delete 请求方式,代码如下:
 function doAjaxDelete(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.open("delete","http://localhost/doAjaxDelete?id=101",true);
        xhr.send(null);
    }
   

启动服务进行访问测试分析

Ajax 技术进阶实现

Ajax 代码的封装

在实际编程过程中我们通常会封装代码共性,提取代码特性.然后来提高代码的可重用性.例如:

  • ajax get 请求,代码如下:
function ajaxGet(url,params,callback) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("GET",params?url+"?"+params:url,true);
    xhr.send(null);
}
  • ajax post 请求,代码如下:
function ajaxPost(url,params,callback) {//add
 let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
}
  • ajax put 请求,代码如下:
function ajaxPut(url,params,callback) {//update
 let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("PUT",url,true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
}
  • ajax delete 请求,代码如下:
function ajaxDelete(url,params,callback) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    xhr.open("delete",params?url+"?"+params:url,true);
    xhr.send(null);
}

Ajax 编程小框架的实现(了解)

我们在实际的js编程中经常会以面向对象的方式进行实现,例如ajaxGet函数,如何以对象方式进行调用呢?关键代码分析如下:(如下代码的理解需要具备JS中面向对象的基础知识,假如不熟可暂时跳过)

(function(){
    //定义一个函数,可以将其连接为java中的类
     var ajax=function(){}
    //在变量ajax指向的类中添加成员,例如doAjaxGet函数,doAjaxPost函数
     ajax.prototype={
        ajaxGet:function(url,params,callback){
        //创建XMLHttpRequest对象,基于此对象发送请求
        var xhr=new XMLHttpRequest();
        //设置状态监听(监听客户端与服务端通讯的状态)
        xhr.onreadystatechange=function(){//回调函数,事件处理函数
            if(xhr.readyState==4&&xhr.status==200){
                //console.log(xhr.responseText);
                callback(xhr.responseText);//jsonStr
            }
        };
        //建立连接(请求方式为Get,请求url,异步还是同步-true表示异步)
        xhr.open("GET",url+"?"+params,true);
        //发送请求
        xhr.send(null);//GET请求send方法不写内容
     },
        ajaxPost:function(url,params,callback){
        //创建XMLHttpRequest对象,基于此对象发送请求
        var xhr=new XMLHttpRequest();
        //设置状态监听(监听客户端与服务端通讯的状态)
        xhr.onreadystatechange=function(){//回调函数,事件处理函数
            if(xhr.readyState==4&&xhr.status==200){
                    //console.log(xhr.responseText);
            callback(xhr.responseText);//jsonStr
            }
        };
        //建立连接(请求方式为POST,请求url,异步还是同步-true表示异步)
        xhr.open("POST",url,true);
       //post请求传参时必须设置此请求头
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        //发送请求
        xhr.send(params);//post请求send方法中传递参数
        }
    }
    window.Ajax=new ajax();//构建ajax对象并赋值给变量全局变量Ajax
})()

此时外界再调用doAjaxGet和doAjaxPost函数时,可以直接通过Ajax对象进行实现。

Ajax 技术在Jquery中的应用

Jquery简介

jQuery是一个快速、简洁的JavaScript库框架,是一个优秀的JavaScript代码库(或JavaScript框架)。jQuery设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。

Jquery中常用ajax函数分析

jQuery中基于标准的ajax api 提供了丰富的Ajax函数应用,基于这些函数可以编写少量代码,便可以快速实现Ajax操作。常用函数有:

  • ajax(…)
  • get(…)
  • getJSON(…)
  • post(…)

Jquery中Ajax函数的基本应用实现

业务描述
构建一个html页面,并通过一些button事件,演示jquery中相关ajax函数的基本应用,如图所示:
image.png

关键步骤及代码设计如下:
第一步:在static目录下添加jquery-ajax-01.html页面.
第二步:在页面上添加关键的html元素,代码如下:

<h1>The Jquery Ajax 01 Page</h1>
<button onclick="doAjax()">$.ajax(...)</button>
<button onclick="doAjaxPost()">$.post(...)</button>
<button onclick="doAjaxGet()">$.get(...)</button>
<button onclick="doAjaxLoad()">$("..").load(...)</button>
<div id="result"></div>
<script src="/js/jquery.min.js"></script>

第三步:添加button事件对应的事件处理函数,代码如下:

  • ajax 函数应用,代码如下:
function doAjax(){
   let url="http://localhost/doAjaxGet";
   let params="";
   //这里的$代表jquery对象
   //ajax({})这是jquery对象中的一个ajax函数(封装了ajax操作的基本步骤)
   $.ajax({
      type:"GET",//省略type,默认就是get请求
      url:url,
      data:params,
      async:true,//默认为true,表示异步
      success:function(result){//result为服务端响应的结果
      console.log(result);//ajax函数内部将服务端返回的json串转换为了js对象
   }//success函数会在服务端响应状态status==200,readyState==4的时候执行.
 });
}
  • post 函数应用,代码如下
function doAjaxPost(){
    let url="http://localhost/doAjaxPost";
    let params="id=101&name=Computer&remark=Computer...";
    $.post(url,params,function(result){
    $("#result").html(result);
});
  • get函数应用,代码如下:
function doAjaxGet(){
    let url="http://localhost/doAjaxGet";
    let params="";
    $.get(url,params,function(result){
      $("#result").html(result);
    },"text");
}
  • load 函数应用,代码如下:
 
function doAjaxLoad(){
    let url="http://localhost/doAjaxGet";
    $("#result").get(url,function(){
      console.log("load complete")
    });
}
 
posted @ 2020-12-09 19:36  Liang-shi  阅读(109)  评论(0编辑  收藏  举报