Ajax进阶-通过构造函数提取共性(三元运算符)

汪睦琴
(()=>{
//1.定义一个构造函数
var ajax=function(){}//函数表达式(可以将其理解为构造函数)
//2.在构造函数内部的原型对象(Prorotype)上添加ajax函数
ajax.prototype={
    doAjax:function(obj){//obj={type:"GET","url":url,"data":params,async:true,"ContentType":ContentType,"success":success,"error":error}
    //1.创建xhr对象
    const xhr=new XMLHttpRequest();
    //2.设置状态监听
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){//服务端响应结束,客户端接收成功
        if(xhr.status==200){//200表示正常响应结束
            obj.success(xhr.responseText);//回调函数
        }else{//表示出现了异常
            obj.error(xhr.status);
        }
    }
}
    //3.建立连接
    let type=obj.type?obj.type:"GET";
    xhr.open(obj.type,obj.type=="GET"?`${obj.url}?${obj.data}`:obj.url,obj.async?true:obj.async);
    //4.发送请求
    if(type!="GET"){
    xhr.setRequestHeader("Content-Type",obj.ContentType?obj.ContentType:"application/x-www-form-urlencoded");
    }
    xhr.send(obj.type=="GET"?null:obj.data);
    },
    doAjaxGet:function(url,params,callback){
    this.doAjax({"type":"GET","url":url,"data":params,"success":callback,"error":callback});
},
    doAjaxPost:function(url,params,callback){
    this.doAjax({"type":"POST","url":url,"data":params,"success":callback,"error":callback,"ContentType":"application/x-www-form-urlencoded"});
    }
}
    //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 05 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/ajaxfk2.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>
阅读 556
4 声望
0 粉丝
0 条评论
4 声望
0 粉丝
文章目录
宣传栏