Simple application of Ajax

mathematics 2020-11-10 11:24:41
simple application ajax


Ajax What is it? ?

Ajax (Asynchronous JavaScript and XML) It's a kind of Web applied technology , You can use client script (javascript) Asynchronous communication with server applications , After getting the server data , Local refresh can be done . In order to improve the data response and rendering speed .

Ajax Technology application scenarios ?

Ajax The biggest advantage of technology is the underlying asynchronous , Then partial refresh , To improve the user experience , This technology is now well used in many projects , for example :

  • Commodity system .
  • Evaluation system .
  • Map system .
  • …..

    AJAX You can just send and retrieve the necessary data to the server , And in the client side JavaScript Processing the response from the server . This reduces the amount of data exchanged between the server and the browser , The server responds faster . but Ajax Technology also has disadvantages , The biggest disadvantage is that cross domain access is not available directly .

    Ajax Request response process analysis


be-all Ajax Requests will be based on DOM(HTML Elements ) event , adopt XHR(XMLHttpRequest) Object implementation and server asynchronous communication, local update , Pictured -4 Shown :

image

chart -4

Based on graph -4 Analysis of ,Ajax The application programming steps are as follows :

First step : be based on dom Event creation XHR object (XMLHttpRequest object )

The second step : register XHR Object state monitoring , Through callback function (callback) Processing status information .

The third step : Create a connection to the server

Step four : Send asynchronous request to realize communication with server

Ajax Entry code easy to implement

Business description , Design the following page , Click... On the page Get Request Button , Send an asynchronous request to the server to get the server data , The response results are then updated to the page .

image

First step : Server side code design

establish AjaxController class , For processing client requests

package com.cy.ajax.controller;@Controller
@RequestMapping("/")
public class AjaxController {
@RequestMapping("doAjax01UI")
public String doAjax01UI() {
return "ajax-01";
          }
// Handle ajax Server side design of the request
@RequestMapping("doAjaxGet")
@ResponseBody // Output the method return value as a string
public String doAjaxGet() throws Exception{
                  System.out.println("==doGet()==");
//Thread.sleep(3000);
// Simulation time operation return "Ajax Get request result";
          }
          
}

The second step : Client code design

Client page key dom Element design :

 <!-- Ajax Mode of asynchronous request testing -->
  <fieldset> <!-- Group settings -->
    <legend> Asynchronous requests </legend>
    <button onclick="doAjaxGet()">Get Request</button>
    <span id="ajaxResultId">loading data ....</span>
  </fieldset>

Key in the client page Ajax Code design and implementation

//Ajax Method request
function doAjaxGet(){
// Error debugging :debugger,console.log(), exclusions
//1. establish XHR object var xhr=new XMLHttpRequest();
//2. Set status monitoring ( Update the result of server response to ajaxResultId Location )
xhr.onreadystatechange=function(){ //console.log(xhr.readState);
if(xhr.readyState==4&&xhr.status==200){
                     console.log(xhr.responseText);
 document.getElementById("ajaxResultId").innerHTML=xhr.responseText;
                }
           };
//3. Establishing a connection
xhr.open("GET","http://localhost/doGet",true);
//true Represents asynchrony ( The bottom layer will start the thread to communicate with the server )
//4. Send a request xhr.send();
}

Ajax Basic business implementation

Basic business description

structure ajax-02 page , First , Register the focus event in the text box , Determine whether the input content exists based on the focus event . Next click save Button , Submit user content asynchronously to the server .
image

Server side key code implementation

On the server AjaxConotroller Add the following code to , Handle client requests :

 private List<String> names=new ArrayList<String>();
// Suppose this is a table that stores data
@RequestMapping("doAjax02UI")
public String doAjax02UI() {
return "ajax-02";
          }
/** Verify the existence of the name by this method */
@RequestMapping("doCheck")
@ResponseBody
public String doCheck(String name) {
if(names.contains(name))
return " name "+name+" Already exist , Please choose another name ";
return " name "+name+" non-existent , You can register ";
          }
/** Write the request to the client names Corresponding set */
@RequestMapping("doSave")
@ResponseBody
public String doSave(String name) {
                  System.out.println("name="+name);
                  names.add(name);
return "save ok";
          }

Client key code implementation

structure ajax-02 page , Then add the key elements .

First step :html Key form element design

 <h1>The Ajax 02 Page</h1>
<fieldset>
   <legend>Ajax Form request </legend>
   <form>
      <input type="text" name="name" id="nameId" onblur="doCheck()" onfocus="doClear()">
      <input type="button" onclick="doSave()" value="Save">
   </form>
   <span id="result"></span>
</fieldset>

The second step : add to JS Key business code

Client key code implementation

structure ajax-02 page , Then add the key elements .

First step :html Key form element design

 <h1>The Ajax 02 Page</h1>
<fieldset>
   <legend>Ajax Form request </legend>
   <form>
      <input type="text" name="name" id="nameId" onblur="doCheck()" onfocus="doClear()">
      <input type="button" onclick="doSave()" value="Save">
   </form>
   <span id="result"></span>
</fieldset>

The second step : add to JS Key business code

<script type="text/javascript">
    function doClear(){
            document.getElementById("result").innerHTML="";
    }
   
    function doSave(){
//1. establish XHR object
var xhr=new XMLHttpRequest();
//2. Set status monitoring
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
              document.getElementById("result").innerHTML="
<font color='red'>"+xhr.responseText+"</font>";
                 }
            };
//3. Open the link
//var name=document.getElementById("nameId").value;
var name=document.forms[0].name.value;
            xhr.open("POST","/doSave",true);
//post Request to set request header ( Regulations )
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4. Send a request xhr.send("name="+name);
//Post request send Method pass value }
   
    function doCheck(){
// In this function, an asynchronous request is made to the server , testing name Whether there is
//1. establish XHR object
var xhr=new XMLHttpRequest();
//2. Set status monitoring
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
                     
document.getElementById("result").innerHTML="<font color='red'>"+xhr.responseText+"</font>";
                }
           };
//3. Open the link
//varname=document.getElementById("nameId").value;
var name=document.forms[0].name.value;
           console.log("name",name);
           xhr.open("GET","/doCheck?name="+name,true);
//4. Send a request
xhr.send(null);
//Get request send Method pass value }
<script type="text/javascript">
    function doClear(){
            document.getElementById("result").innerHTML="";
    }
   
    function doSave(){
//1. establish XHR object
var xhr=new XMLHttpRequest();
//2. Set status monitoring
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
                     
document.getElementById("result").innerHTML="<font
color='red'>"+xhr.responseText+"</font>";
                 }
            };
//3. Open the link
//varname=document.getElementById("nameId").value;
var  name=document.forms[0].name.value;
            xhr.open("POST","/doSave",true);
//post Request to set request header ( Regulations ) xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4. Send a request xhr.send("name="+name);//Post request send Method pass value }
   
    function doCheck(){
// In this function, an asynchronous request is made to the server , testing name Whether there is
//1. establish XHR object
var xhr=new XMLHttpRequest();
//2. Set status monitoring
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
                     document.getElementById("result").innerHTML="<font color='red'>"+xhr.responseText+"</font>";
                }
           };
//3. Open the link
//varname=document.getElementById("nameId").value;
var  name=document.forms[0].name.value;
           console.log("name",name);
           xhr.open("GET","/doCheck?name="+name,true); //4. Send a request xhr.send(null);//Get request send Method pass value }

Ajax Advanced technology implementation

Ajax Encapsulation of key code

In actual programming, we usually encapsulate code commonalities , Extract code features . Then to improve the reusability of the code . for example :

First step : encapsulation AJax Get request , The key code analysis is as follows :

function doAjaxGet(url,params,callback){
//1. establish XmlHttpRequest object
var xhr=new XMLHttpRequest();
//2. Set status monitoring , monitor XmlHttpRequest Object and server communication process ( For example, whether the connection is established , Whether the request is being processed , Whether the response has been generated )
xhr.onreadystatechange=function(){//callback( Callback function )
// be based on xhr Object gets the communication state of , Process the response data
//readyState Status description
//0: uninitialized , Not yet invoked open() Method
//1: start-up . Has called open() Method , But not yet called send() Method
//2: send out . Has called send() Method , But no response has been received
//3: receive . Partial response has been received
//4: complete . All response data has been received , And it can be used in the client
if(xhr.readyState==4&&xhr.status==200){
//500 Indicates that the server has made a mistake
// The result of the server response will be passed to XHR object , We can use responseText Get response results
callback(xhr.responseText);
         }
     }
//3. Create a connection to the server xhr.open("GET",url+"?"+params,true);
//true Represents asynchrony
//4. Send a request
xhr.send(null);
//Get request ,send Methods don't pass content
//5. Process response results ( Handle in callback function ).
}

The second step : encapsulation AJax Post request , The key code analysis is as follows :

 function doAjaxPost(url,params,callback){
//1. establish XmlHttpRequest object
var xhr=new XMLHttpRequest();
//2. Set status monitoring , monitor XmlHttpRequest Object and server communication process . xhr.onreadystatechange=function(){
//callback( Callback function )
// be based on xhr Object gets the communication state of , Process the response data if(xhr.readyState==4&&xhr.status==200){
//500 Indicates that the server has made a mistake
// The result of the server response will be passed to XHR object ,
// We can use xhr.responseText Get response results callback(xhr.responseText);
                 }
         }
//3. Create a connection to the server
xhr.open("POST",url,true);
//true Represents asynchrony
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//4. Send a request xhr.send(params);
//post Request to write parameters to send Method
//5. Process response results ( Handle in callback function ).
}

The third step : Good methods are applied in business code , for example :

The key client code analysis and implementation of preservation business .

 function doSave(){
//1. Define request url
var url="doSave";
//2. Define request parameters
var params="name="+document.forms[0].name.value;
//3. Send asynchronous post request
doAjaxPost(url,params,function(result){
  document.getElementById("result").innerHTML=result;
           })
    }

Key client code implementation to check if the name exists

 function doCheck(){
// In this function, an asynchronous request is made to the server , testing name Whether there is
//1. Define request url
var url="doCheck";
//2. Define request parameters
var name=document.forms[0].name.value;
        var params="name="+name;
//3. Send asynchronously Get request
doAjaxGet(url,params,function(result){
document.getElementById("result").innerHTML=result;
        })
    }

Ajax The programming framework is basically implemented ( understand )

We're actually js Programming is often implemented in an object-oriented way , for example 2.3 In the chapter doAjaxGet How can functions be applied in object methods ? The key code analysis is as follows :

(function(){
// Define a function , It can be connected as java Class in
var ajax=function(){}
// In variables ajax Add a member to the class pointed to , for example doAjaxGet function ,doAjaxPost function
ajax.prototype={
           doAjaxGet:function(url,params,callback){
// establish XMLHttpRequest object , Send a request based on this object
var xhr=new XMLHttpRequest();
// Set status monitoring ( Monitor the status of communication between client and server )
xhr.onreadystatechange=function(){
// Callback function , Event handler
if(xhr.readyState==4&&xhr.status==200){
//console.log(xhr.responseText);
callback(xhr.responseText);
//jsonStr }
                      };
// Establishing a connection ( The request method is Get, request url, Asynchronous or synchronous -true Represents asynchrony )
xhr.open("GET",url+"?"+params,true);
// Send a request
xhr.send(null);
//GET request send Methods don't write content
},
              doAjaxPost:function(url,params,callback){
// establish XMLHttpRequest object , Send a request based on this object
var xhr=new XMLHttpRequest();
// Set status monitoring ( Monitor the status of communication between client and server )
xhr.onreadystatechange=function(){
// Callback function , Event handler
if(xhr.readyState==4&&xhr.status==200){
//console.log(
xhr.responseText);
callback(xhr.responseText);
//jsonStr
}
                      };
// Establishing a connection ( The request method is POST, request url, Asynchronous or synchronous -true Represents asynchrony )
xhr.open("POST",url,true);
//post This request header must be set when requesting parameter transmission
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// Send a request
xhr.send(params);
//post request send Method }
        }
        window.Ajax=new ajax();
})()

Ajax Technology in Jquery Application in

Jquery brief introduction

jQuery It's a fast one 、 concise JavaScript frame , Is an excellent one JavaScript The code base ( or JavaScript frame ).jQuery The purpose of the design is “write Less,Do More”, That is to say, write less code , Do more . It encapsulates JavaScript Common function codes , Provides a simple JavaScript Design patterns , Optimize HTML The document operation 、 Event handling 、 Animation design and Ajax Interaction .

query Commonly used Ajax function

jQuery Based on standards ajax api Provides a wealth of Ajax Function application , Based on these functions, you can write a small amount of code , It can be realized quickly Ajax operation . Common functions are :

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

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

Jquery Commonly used Ajax Function application case sharing

get Function application , The code is as follows

// Send to server Ajax Get request
function doGet(){
//1. Define the requested url
var url="doAjaxGet";
//2. Define the parameters of the request
var params="msg=hello jquery ajax get";
//3. Send asynchronously Get request
// there $ The symbol is jQuery One of the objects in
//get(url[,params][,callback][,dataType]) by jquery One of them ajax function
$.get(url,params,function(result){
//document.getElementById("result").innerHTML=result;
$("#result").html(result);
             },"text");// You see in this function ajax Is the code for ? }

post Function application , The code is as follows

 // Send to server Ajax Post request
function doPost(){
//1. Define the requested url
var url="doAjaxPost";
//2. Define the parameters of the request
var params="msg=hello jquery ajax Post";
//3. Send asynchronously POST request
// there $ The symbol is jQuery One of the objects in
//post(url[,params][,callback][,dataType]) by jquery One of them ajax function
$.post(url,params,function(result){
//post Requests are generally used to submit data to the server
$("#result").html(result);
           
});
// You see in this function ajax Is the code for ? }

ajax Function application

 // Send to server Ajax Post request
function doAjax(){
//1. Define the requested url var url="doAjaxGet";
//2. Define the parameters of the request
var params="msg=hello jquery ajax request";
//3. Send asynchronously Get request
// there $ The symbol is jQuery One of the objects in
$.ajax({
        type:"GET",
// Express get request ( The default is get), Omit and not write as Get
url:url,
//":" On the left is the grammatical definition , We can't modify .":" On the right, we define ourselves
data:params,
// Request parameters
async:true,
//true Represents asynchrony
success:function(result){
// Callback function
$("#result").html(result);
                     }
             });
// You see in this function ajax Is the code for ? }

load Function application

 function doLoad(){
//1. Define the requested url
var url="doAjaxGet";
//2. Define the parameters of the request
var params="msg=hello jquery ajax request";
//3. Send asynchronously Get request
// Load asynchronously at the specified location url Object resources ,
// In the current application, it means to put url Object's resources are presented to #result Location .
//$("#result").load(url,params,function(){
// Callback function , The resource loading is completed and this function is executed
//  console.log("load complete");
//});
$("#result").load(url);
// If you don't pass values to the server , No need to deal with load The result after that , You can also write }

summary

Analysis of key and difficult points

  1. The request response model of communication between client and server ?( Sync , asynchronous )
  2. Ajax The basic steps of programming ( Entry object -XMLHttpRequest),Ajax Application scenarios ?
  3. JQuery In the frame ajax Basic applications of functions ?(ajax(),get(),getJSON(...).....)
  4. JS Breakpoints in the coding process (debugger) The application of ?

FAQ analysis

  1. Ajax What are the advantages of Technology , Inferiority ?( advantage : Load asynchronously on demand , Partial update , Improve user experience )
  2. Ajax The core object of Technology ?(XMLHttpRequest- Entry object )
  3. client JS How to debug ?( Pile driving console.log(),debugger, exclusions )
  4. For some js Frame how you learn ? Official website (,demo, practice - Browser Test , Search engine )

BUG analysis

  1. Misspelling of words , Pictured -7 Shown :

image

chart -7

Problem analysis : Click... In the error prompt 54 Line code , Look at the spelling mistakes , Check param Where does the word define .

  1. Missing brackets , Pictured -8 Shown

image

chart -8

Problem analysis : Click... In the error prompt 59 Line code , See if you've lost parentheses “)”.

版权声明
本文为[mathematics]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple