Ajax和jsonp的封装

   ajax({
            type:get,                           // 可选 默认为get方式
            url:url,                               //传输到的地址  必填
            succes:function(){},         // 成功后返回的数据  要得到数据必填
            error:function(){},            //失败后返回的失败的数据 选填
            data:{name:'name',             // 传入的数据  选填。
                pass:123,
                cb:'hhh',
                columName:cb,               //后端的交互的时候函数名(重要)!!
            }
   })

ajax和jsonp的函数

function ajax(opts){
       var {type,url,success,error,data} = opts;

          type = type||"get";
          data = data || {};
          //判断是否为get或者为json属性 是就拼接
          var str = "";
          for(var i in data){
              str += `${i}=${data[i]}&`; 
          }
          if(type=="get" ){
           
              var d = new Date();
              //拼接data里面的属性和属性值。
            
              url =  url +'?' +str +d.getTime();   //拼接url的地址
        } //if判断类型的结束

        if(type== "jsonp"){
          //  console.log(str);
            var script = document.createElement('script');
            url =  url +'?'+str;
          //   console.log(url);
            script.src = url;
            document.body.appendChild(script);
            window[data[data.clouName]]= function(res){
                  success(res);
      }
           
        }else{
          var xhr = new XMLHttpRequest();
          xhr.open(type,url,true);
          xhr.onreadystatechange = function(){
              if(xhr.status == 200 && xhr.readyState == 4){
                          success(xhr.responseText);
              }else if(xhr.status!= 200&&xhr.readyState==4){
                  error && error(xhr.responseText);
              }
          }  //ifelse的结束
          if(type=="get"){
              xhr.send();
          }else if(type == "post"){
              xhr.setRequestHeader("Content-Type",
               "application/x-www-form-urlencoded");
               xhr.send(str.slice(0,str.length-1));
          }
        }
      }

你可能感兴趣的:(Ajax和jsonp的封装)