AJAX routine application summary

Ajax technology application

Introduction to Ajax Technology

background

Today, with the rapid development of the Internet, traditional WEB applications have urgent requirements for high concurrency, high performance, and high reliability. The single-threaded interaction between the client and the server can no longer meet the needs of the current stage. We need to obtain data from the server in an asynchronous, on-demand loading manner and refresh it in time to improve the user experience, so Ajax technology was born.

Ajax overview

Ajax (Asynchronous JavaScript and XML) is a web application client technology that can use client script (javascript) to communicate asynchronously with the server application (multiple threads can interact with the server at the same time), and obtain server data on demand Later, partial refresh can be performed to improve the data response and rendering speed.

Ajax application scenario analysis

The biggest advantage of Ajax technology is that the underlying is asynchronous, and then partially refreshed, thereby improving the user experience. This technology is now well applied in many projects, such as:

  • Commodity system.
  • evaluation system.
  • Map system.
  • ……

AJAX can only send and retrieve necessary data to the server, and use JavaScript on the client to process the response from the server. In this way, the data exchanged between the server and the browser is greatly reduced, and the server responds faster. However, Ajax technology also has disadvantages. The biggest disadvantage is that it cannot directly conduct cross-domain access.

Ajax technology quick start

Ajax request response model

The traditional way is web request and response (the client has to wait for the response result), as shown in the figure:

image.png

Ajax request and response (the key is that the client does not block), as shown in the figure:

image.png

Ajax template code (four steps)

Analysis of programming steps: (The focus is on the entry of ajax technology-XMLHttpRequest-XHR object)

Step 1: Create an XHR object based on the dom event
Step 2: Register a status monitor on the XHR object (monitor the communication process between the client and the server)
Step 3: Establish a connection with the server (specify the request method, request url, synchronize or Asynchronous)
Step 4: Send the request (pass the request data to the server)

Template code analysis:

let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
   if(xhr.readyState==4){
      if(xhr.status==200){
         console.log(xhr.responseText);
      }
   }
}
xhr.open("GET",URL,TRUE);
xhr.send(null);

Quick practice of Ajax request in Spring project

Step 1: business description

By triggering the button on the page, an ajax request is sent to the server, and the server response result is updated to the page through a partial update method, as shown in the figure:

Step 2: Create the project module, as shown in the figure:

image.png

The third step is to add project web dependencies

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

Step 4: Create an AjaxController to handle client requests, the code is as follows:

package com.cy.pj.ajax.controller;
@RestController
public class AjaxController{
      @GetMapping("/doAjaxStart")
      public String doAjaxStart(){
          return "request ajax start result"
      }
}

Step 5: In the static directory of the project, create a page ajax-01.html, the code is as follows:

The html element code is as follows:

<div>
   <h1>The Ajax 01 page</h1>
   <button onclick="doAjaxStart()">do ajax start</button>
   <span id="result"></span>
</div>

The javascript script elements are as follows:

 <script>
       //js中问题的解决方案:console.log(),debugger,排除法
       function doAjaxStart(){
          debugger //js中断点
          //初始化span标记内部内容(可选)
          let span=document.getElementById("result");
          span.innerHTML="Data is loading....."
         //创建XHR对象
          let xhr=new XMLHttpRequest();
         //设置状态监听
          xhr.onreadystatechange=function(){
              if(xhr.readyState==4&&xhr.status==200){
                  span.innerHTML=xhr.responseText;
              }
          }
           const url="http://localhost/doAjaxStart";
          //建立连接
           xhr.open("GET",url,true);//true 表示异步
          //发送请求
           xhr.send(null);
       }
  </script>

Among them, readyState4 indicates that the data from the server to the client has been received, status200 means the server processing is OK, 500 means abnormal.

The sixth step is to start the service for access testing.

Start the service, open the browser and enter http://localhost/ajax-01.html, click the page button to access, and check the output, as shown in the figure:

Ajax technology basic business realization

Business description

Create an ajax-02 page, add get, post, delete, put request buttons on the page, send an ajax asynchronous request to the server when the button is triggered, and process the response result, as shown in the figure:

Server design and implementation

Add the code for processing ajax requests in AjaxController. The key codes are as follows:

Initial data preparation

Add the List property (simulating database) to the AjaxController and initialize the data through the constructor. The key code is as follows:

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);
}

Add server-side business code for processing Get requests

@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;
}

Add server-side business code for processing post requests

@PostMapping("/doAjaxPost")
public String doAjaxPost(@RequestParam Map<String,String>  map){
     dbList.add(map);
     return "save ok";
}

If the client is a post request, and the json format string is passed to the server, our code needs to be designed in the following way

@PostMapping("/doAjaxPostJson")
public String doAjaxPost(@RequestBody Map<String,String>  map){
     dbList.add(map);
     return "save ok";
}

Add server-side business code for processing put requests (usually used for updates)

@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";
}

Add the code to handle the delete request

    @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";
    }

Client design and implementation

Create ajax-02.html page, its key html elements are as follows:

<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>

AjaxGet request method, the key code is as follows:

function doAjaxGet(){
          //1.创建XHR对象
          let xhr=new XMLHttpRequest();
          //2.设置状态监听
          xhr.onreadystatechange=function(){
              if(xhr.readyState==4){
                  if(xhr.status==200){
                    let div=document.getElementById("result");
                    div.innerHTML=xhr.responseText;
                  }
              }
          }
          //3.建立连接
          //let params="b";
          let params="";
          xhr.open("Get",`http://localhost/doAjaxGet/${params}`,true);
          //4.发送请求
          xhr.send(null);
      }

Ajax Post request method, the key code is as follows:

  function doAjaxPost(){
          //1.创建XHR对象
          let xhr=new XMLHttpRequest();
          //2.设置状态监听
          xhr.onreadystatechange=function(){
              if(xhr.readyState==4){
                  if(xhr.status==200){
                      let div=document.getElementById("result");
                      div.innerHTML=xhr.responseText;
                  }
              }
          }
          //3.建立连接
          let params="id=102&city=shenzhen"
          xhr.open("post",`http://localhost/doAjaxPost`,true);
          //post请求必须要设置请求头
          xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
          //4.发送请求
          xhr.send(params);//post请求可以将参数放到send方法内部
  }

Ajax Post request code, send JSON format data to the server, the key code is as follows:

      function doAjaxPostJson(){
          //1.创建XHR对象
          let xhr=new XMLHttpRequest();
          //2.设置状态监听
          xhr.onreadystatechange=function(){
              if(xhr.readyState==4){
                  if(xhr.status==200){
                      let div=document.getElementById("result");
                      div.innerHTML=xhr.responseText;
                  }
              }
          }
          //3.建立连接
          let params={id:103,city:"xiongan"}
          let paramsStr=JSON.stringify(params);//将json对象转换为json字符串
          console.log("jsonStr",paramsStr);
          xhr.open("post",`http://localhost/doAjaxPostJSON`,true);
          //post请求必须要设置请求头
          xhr.setRequestHeader("Content-Type","application/json");
          //4.发送请求
          xhr.send(paramsStr);//post请求可以将参数放到send方法内部
      }

The key code of the Ajax Delete request method is as follows:

   function doAjaxDelete(){
          //1.创建XHR对象
          let xhr=new XMLHttpRequest();
          //2.设置状态监听
          xhr.onreadystatechange=function(){
              if(xhr.readyState==4){
                  if(xhr.status==200){
                      let div=document.getElementById("result");
                      div.innerHTML=xhr.responseText;
                  }
              }
          }
          //3.建立连接
          //let params="b";
          let params="102";
          xhr.open("delete",`http://localhost/doAjaxDelete/${params}`,true);
          //4.发送请求
          xhr.send(null);
  }

Ajax Put request method, the key code is as follows:

  function doAjaxPut(){
          //1.创建XHR对象
          let xhr=new XMLHttpRequest();
          //2.设置状态监听
          xhr.onreadystatechange=function(){
              if(xhr.readyState==4){
                  if(xhr.status==200){
                      let div=document.getElementById("result");
                      div.innerHTML=xhr.responseText;
                  }
              }
          }
          //3.建立连接
          let params="id=101&city=tianjin"
          xhr.open("put",`http://localhost/doAjaxPut`,true);
          //put请求必须要设置请求头
          xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
          //4.发送请求
          xhr.send(params);//put请求可以将参数放到send方法内部
  }

Start the service and perform an access test.

Advanced implementation of Ajax technology (package commonality)

Encapsulation of common template code

In the actual programming process, we usually encapsulate the commonalities of the code and extract the code features. Then to improve the reusability of the code. For example, create a js directory in the static directory and add the ajax.js file. The key code is as follows:

Creation of xhr object

function createXHR(callback){
    //1.create XHR object
    let xhr=new XMLHttpRequest();
    //2.set onreadystatechange
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                callback(xhr.responseText);
            }
        }
    }
    return xhr;
}

Get request

function ajaxGet(url,params,callback){//封装ajax get 请求模板代码
    //1.create xhr and set onreadystate change
    let xhr=createXHR(callback);
    //2.open connection
    xhr.open("GET",`${url}/${params}`,true);
    //3.send request
    xhr.send();
}

Post request

function ajaxPost(url,params,callback){//封装ajax get 请求模板代码
    //1.create xhr and set onreadystate change
    let xhr=createXHR(callback);
    //2.open connection
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //3.send request
    xhr.send(params);
}

post request, pass json data

function ajaxPostJSON(url,params,callback){
    //1.create xhr and set onreadystate change
    let xhr=createXHR(callback);
    //2.open connection
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type","application/json");
    //3.send request
    xhr.send(JSON.stringify(params));//将json对象转换为json格式字符串提交到服务端
}

Put request

function ajaxPut(url,params,callback){//封装ajax get 请求模板代码
    //1.create xhr and set onreadystate change
    let xhr=createXHR(callback);
    //2.open connection
    xhr.open("put",url,true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //3.send request
    xhr.send(params);
}

delete request

function ajaxDelete(url,params,callback){//封装ajax get 请求模板代码
    //1.create xhr and set onreadystate change
    let xhr=createXHR(callback);
    //2.open connection
    xhr.open("delete",`${url}/${params}`,true);
    //3.send request
    xhr.send();
}

Create the ajax-03.html page, call the above functions in the page to access the test, the key code is as follows:

 <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 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>

Simple implementation of Ajax programming framework (understand)

We often implement it in an object-oriented way in actual js programming, such as the ajaxGet function, how to call it in an object way? The key code analysis is as follows: (The understanding of the following code requires basic knowledge of object-oriented in JS, if you are not familiar with it, you can skip it temporarily)

(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
})()

At this time, when the outside world calls the doAjaxGet and doAjaxPost functions, it can be implemented directly through the Ajax object.

Application of Ajax Technology in JQuery Framework

Introduction

jQuery is a fast and concise JavaScript library framework and an excellent JavaScript code library (or JavaScript framework). The purpose of jQuery design is "write Less, Do More", that is, advocating to write less code and do more things. It encapsulates JavaScript commonly used function codes, provides a simple JavaScript design mode, optimizes HTML document operation, event handling, animation design and Ajax interaction.

Analysis of commonly used ajax functions

The standard-based ajax api in jQuery provides a wealth of Ajax function applications. Based on these functions, a small amount of code can be written to quickly implement Ajax operations. Commonly used functions are:

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

Note: For the syntax of ajax related functions in jquery, please refer to the official website (jquery.com).

Application practice of ajax function in Jquery

Business description
Build an html page, such as jquery-ajax-01.html, and demonstrate the basic application of related ajax functions in jquery through some button events, as shown in the figure:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-BerbiC9s-1611209329048)(D:\TCGBIII\DEVDOCS\Day10\ajax.assets\image-20210105183916162.png) ]

Analysis of the client's key html code implementation

   <div>
       <h1>The Jquery Ajax 01 Page</h1>
       <button onclick="doAjax()">$.ajax(...)</button>
       <button onclick="doGet()">$.get(...)</button>
       <button onclick="doPost()">$.post(...)</button>
       <button onclick="doLoad()">$(...).load("...")</button>
   </div>
   <div id="result"></div>

Analysis of the realization of key JS code codes on the client side

<script src="/js/jquery.min.js"></script>
<script>
    function doLoad(){
           let requestUrl="/doAjaxGet";
           //load函数会在指定位置通过ajax方法加载数据,并将数据更新到这个位置
           $("#result").load(requestUrl,function(){//可选
               console.log("==load complete==");//加载完成以后执行
           });
     }
     function doPost(){
           let requestUrl="/doAjaxPost";
           let params="id=104&city=shijiazhuang";
           $.post(requestUrl,params,function(result){
               alert(result);
           })
     }
     function doGet(){
           let requestUrl="/doAjaxGet";
           let params="";
           $.get(requestUrl,params,function(result){
               $("#result").html(result);
           },"text");//默认为json
     }

     function doAjax(){
          let requestUrl="/doAjaxGet";
          let params="";
          //$符号在这里代表jquery对象
          //ajax({})为jquery种的一个ajax函数,底层封装了ajax请求过程
          $.ajax({
              url:requestUrl,//key必须为url
              data:params,
              //type:"GET",//可以省略,默认为Get请求
              dataType:"text",//服务端响应到客户端的数据格式,默认为json
              //async:true,//默认异步
              //contentType:"application/json",//假如需要向服务端传递json串
               success:function(result){//callback 回调函数
                  console.log("result",result);
                  //JS原生写法
                  //document.querySelector("#result").innerHTML=result;
                  //Jquery种的封装简化写法
                  $("#result").html(result);
              }
          });
          //假如服务端响应到客户端的数据为json格式字符串,底层会默认将其转换为json对象
       }
</script>

Guess you like

Origin blog.csdn.net/weixin_40597409/article/details/112939854