咱们在理论编程中常常会以面向对象的形式进行实现。
新建static-->js-->ajaxfk.js,在该js文件中增加如下代码:

(()=>{//1.定义一个构造函数var ajax=function(){}//函数表达式(能够将其了解为构造函数)//2.在构造函数外部的原型对象(Prorotype)上增加ajax函数ajax.prototype={doAjaxGet:function(url,params,callback){//1.创立xhr对象const xhr=new XMLHttpRequest();//2.设置状态监听xhr.onreadystatechange=function(){    if(xhr.readyState==4){//服务端响应完结,客户端接管胜利    if(xhr.status==200){//200示意失常响应完结        callback(xhr.responseText);//回调函数    }else{//示意呈现了异样        callback(xhr.status);        }    }}//3.建设连贯xhr.open("GET",`${url}?${params}`,true);//4.发送申请xhr.send(null);},doAjaxPost:function(url,params,callback){//1.创立xhr对象const xhr=new XMLHttpRequest();//2.设置状态监听xhr.onreadystatechange=function(){    if(xhr.readyState==4){//服务端响应完结,客户端接管胜利    if(xhr.status==200){//200示意失常响应完结        callback(xhr.responseText);//回调函数    }else{//示意呈现了异样        callback(xhr.status);        }    }}//3.建设连贯xhr.open("POST",url,true);xhr.setRequestHeader("Content-Type","application/x-www.urlencoded");//4.发送申请xhr.send(params);    }}//3.基于ajax构造函数构建ajax对象,并将对象赋值给全局变量window.$$=new ajax();})()//箭头函数

批改html代码:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><h1>The Ajax 04 Page</h1><fieldset><legend>Ajax 表单申请</legend><form>   <input type="text" id="nameId" name="name" onblur="doCheck()">   <input type="button" onclick="doSave()" value="Save"></form><span id="resultId"></span><!-- 此地位显示服务端响应后果 --></fieldset><script type="text/javascript" src="/js/ajaxfk.js"></script><script type="text/javascript">   //检测名字是否已存在   function doCheck(){       //1.定义申请的url       var url="http://localhost/doCheck";       //2.定义申请参数       var name=document.forms[0].name.value;       var params=`name=${name}`;       //3.发送ajax get申请       $$.doAjaxGet(url,params,(result)=>{           document.getElementById("resultId").innerHTML=               `<font color=red>${result}</font>`;       });   }   //保留表单中名字的值   function doSave(){//debugger,log,排除法      //1.申请url      const url="http://localhost/doSave";      //2.申请参数      let name=document.forms[0].name.value;      let params=`name=${name}`;      //3.发送ajax post申请      $$.doAjaxPost(url,params,(result)=>{            alert(result);      })   }</script></body></html>