关于ajax: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>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理