Ajax 技术应用

Ajax技术应用

1、Ajax简介

1.1 Ajax是什么?

######## Ajax(Asynchronous JavaScript and XML) 是一种Web应用技术,可以借助客户端脚本(JavaScript)与服务端应用进行异步通讯,获取服务端数据以后,可以进行局部刷新。进而提高数据的响应和渲染速度。
######## 传统Web应用中简易的同步模型分析,如图-1所示:
在这里插入图片描述
####### 基于Ajax技术的异步请求响应模型分析,如图-2所示:
在这里插入图片描述

1.2Ajax 技术应用场景?

######## Ajax 技术最大的优势就是底层异步,然后局部刷新,进而提高用户体验,这种技术现在在
很多项目中都有很好的应用,例如:
❏ 商品系统。
❏ 评价系统。
❏ 地图系统。
❏ ……
AJAX 可以仅向服务器发送并取回必要的数据,并在客户端采用 JavaScript 处理来自
服务器的响应。这样在服务器和浏览器之间交换的数据大量减少,服务器响应的速度就更快
了。但 Ajax 技术也有劣势,最大劣势是不能直接进行跨域访问。

1.3Ajax 技术时序模型分析?

####### 传统 Web 应用中的,同步请求应用时序模型分析,如图-3 所示:
在这里插入图片描述
在图-3 中,客户端向服务端向服务端发送请求需要等待服务端的响应结果,服务端返
回数据以后,客户端可以继续发送请求。

############ 基于 Ajax 技术的 Web 异步请求响应模型如图-4 所示:
在这里插入图片描述
######## 在图-4 中,客户端可以向服务端发送异步请求,客户端无需等待服务端的响应结果,
可以不断向服务端发送请求。

2.Ajax 快速入门

2.1 Ajax 请求响应过程分析

####### 所有的 Ajax 请求都会基于 DOM(HTML 元素)事件,通过 XHR(XMLHttpRequest)对
象实现与服务端异步通讯局部更新,如图-4 所示:

基于图-4 的分析,Ajax 应用的编程步骤如下:
第一步:基于 dom 事件创建 XHR 对象(XMLHttpRequest 对象)
第二步:注册 XHR 对象状态监听,通过回调函数(callback)处理状态信息。
第三步:创建与服务端的连接
第四步:发送异步请求实现与服务端的通讯
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);

2.2 Ajax 入门代码简易实现

######## 业务描述,设计如下页面,在页面上点击 Get Request 按钮时,向服务端发送异步请求获取服务端数据,然后将响应结果更新到页面上.
第一步:创建项目module;
第二步:添加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会继续向下执行.
}

第五步:启动Tomcat服务并进行访问测试分析.

点击Ajax Get Request 按钮,检测页面数据更新.

第六步:启动及访问过程中的Bug分析

点击按钮没反应

访问指定属性的对象不存在

跨域访问

3. Ajax 基本业务实现

3.1 基本业务描述

构建 ajax-02 页面,首先,在文本框中注册焦点事件,基于焦点事件判断输入内容是否存在.其次点
击 save 按钮时,将用户内容异步提交到服务器端.
在这里插入图片描述

3.2 服务端关键代码实现

在服务端 AjaxConotroller 中添加如下代码,处理客户端请求:

/**假设这个是用于存储数据的数据库*/
    private List<Map<String,String>> dbList=new ArrayList<>();
    public AjaxController(){
    Map<String,String> map=new HashMap<String,String>();
    map.put("id","100");
    map.put("city","beijing");
    dbList.add(map);
    map=new HashMap<String,String>();
    map.put("id","101");
    map.put("city","shanghai");
    dbList.add(map);
    }

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

@GetMapping(path={"/doAjaxGet/{city}","/doAjaxGet")
public List<Map<String,String> doAjaxGet(@PathVariable(required=false) String city){
   List<Map<String,String>> list=new ArrayList<>();
   for(Map<String,String> map:dbList){
        if(map.get("city").contains(city)){
             list.add(map);
        }
    }
    return list;
}
@PostMapping("/doAjaxPost")
public String doAjaxPost(@RequestParam Map<String,String>  map){
     dbList.add(map);
     return "save ok";
}
@PostMapping("/doAjaxPostJson")
public String doAjaxPost(@RequestBody Map<String,String>  map){
     dbList.add(map);
     return "save ok";
}

@DeleteMapping("/doAjaxDelete/{id}")
public String doDeleteObject(@PathVariable  String id){
      //基于迭代器执行删除操作
      Iterator<Map<String,String>> it=dbList.iterator();
      while(it.hasNext()){
        Map<String,String> map=it.next();
           if(map.get("id").equals(id)){
                 it.remove();//基于迭代器执行删除操作
              }
     }
     return "delete ok";
}
    
@PostMapping("/doAjaxPut")
public String doAjaxPut(@RequestParam Map<String,String>  paramMap){
     for(Map<String,String> map:dbList){
          if(map.get("id").equals(paramsMap.get("id"))){
               map.put("city",paramMap.get("city"))
          }
     }
     return "update ok";
}

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

在static目录下创建ajax-02.html文件,关键代码如下:
<div>
    <h1>The Ajax 02 Page</h1>
    <button onclick="doAjaxGet()">Do Ajax Get</button>
    <button onclick="doAjaxPost()">Do Ajax Post</button>
    <button onclick="doAjaxPostJson()">Do Ajax Post Json</button>
    <button onclick="doAjaxDelete()">Do Ajax Delete</button>
    <button onclick="doAjaxPut()">Do Ajax Put</button>
</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;
               }
           }
       }
       let params=""
       xhr.open("GET",`http://localhost/doAjaxGet/${params}`,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=102&city=shenzhen");
}
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/json");
        //发送请求(post请求传递数据,需要将数据写入到send方法内部)
        let params={id:103,city:"xiongan"};
        let paramsStr=JSON.stringify(params);
        xhr.send(paramsStr);
}

Update 请求方式,代码如下:

 function doAjaxPut(){
    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/doAjaxPut",true);
     //post请求向服务端传递数据,需要设置请求头,必须在open之后
     xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     //发送请求(post请求传递数据,需要将数据写入到send方法内部)
     xhr.send("id=101&city=tianjin");
    }

Delete 请求方式,代码如下:

 function doAjaxDelete(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        let params="102";
        xhr.open("delete",`http://localhost/doAjaxDelete/${params}`,true);
        xhr.send(null);
    }
   
创建ajax-03.html页面,在页面中分别调用如上函数进行访问测试,关键代码如下:
<div>
      <h1>The Ajax 03 Page</h1>
      <button onclick="doAjaxGet()">Do Ajax Get</button>
      <button onclick="doAjaxPost()">Do Ajax Post</button>
      <button onclick="doAjaxPostJson()">Do Ajax Post Json</button>
      <button onclick="doAjaxDelete()">Do Ajax Delete</button>
      <button onclick="doAjaxPut()">Do Ajax Put</button>
  </div>
  <div id="result"></div>
  <script class="lazy" data-src="/js/ajax.js"></script>
  <script>
      //ajax delete request
      function doAjaxDelete(){
          const url="/doAjaxDelete";
          const params="101";
          ajaxDelete(url,params,function(result){
              alert(result);
          })
      }
      //ajax post put
      function doAjaxPut(){
          const url="/doAjaxPut";
          const params="id=100&city=shenzhen";
          ajaxPut(url,params,function(result){
              alert(result);
          })
      }
      //ajax post request
      function doAjaxPostJson(){
          const url="/doAjaxPostJSON";
          const params={id:"103",city:"xiongan"};//服务端需要@RequestBody
          ajaxPostJSON(url,params,function(result){
              alert(result);
          })
      }
      //ajax post request
      function doAjaxPost(){
          const url="/doAjaxPost";
          const params="id=102&city=shenzhen";
          ajaxPost(url,params,function(result){
              alert(result);
          })
      }
      //ajax get request
      function doAjaxGet(){
          const url="/doAjaxGet";
          const params="";
          ajaxGet(url,params,function(result){
              document.querySelector("#result").innerHTML=result;
          })
      }

  </script>
  

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相关函数的语法可参考官网(jquery.com).

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

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

关键步骤及代码设计如下:
第一步:在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 class="lazy" data-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")
    });
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值