我们在实际编程中经常会以面向对象的方式进行实现。
新建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>

汪睦琴
4 声望0 粉丝