页面 ajax

let xhr;

if(XMLHttpRequest){

   xhr = new XMLHttpRequest;

}else{

    xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

let  dataStr=jsonToString(data);//数据的传输以JSON格式,需要转换成string格式,才能在js代码中进行编写。

//在服务端发起请求时,请求方式分为get和post两种,是可以向服务端传递数据的

//GET 请求:传递的数据是跟在 open ⽅法中的 url 后⾯。

if(type.toUppercase()==''GET'){ 

    xhr.open(type,url+"?"+dataStr, async);

    xhr.send();

}else{

//POST 请求:传递的数据是放在 send ⽅法的参数中。

     xhr.open(type , url , async );

    xhr.send(dataStr); //等于xhr.send("name='zs'&age='18'");

}

xhr.onreadystatechange = function(){

      //log(xhr.readyState);//测试状态是否输出了

    if(xhr.readyState ==4 && ((xhr.sttus>=200 xhr.sttus<300) || xhr.status==304)){

            let data=xhr.responseText;

            success(data);//success回调函数

        }

  }

function jsonToString(obj){

   let arr=[ ];

   for(const key in obj){

      const value=obj[key];

      arr.push(`${key},${value}`);

     }

    return arr.join("&");

}

ajax({

    type:"GET";

    url:“https://getman.cn/mock/,,,”,

    data:{name:"zs", age:18},

    sucess(data){ console.log("daying ",data)}

});

getman.cn/mock/

猜你喜欢

转载自www.cnblogs.com/yt0817/p/12007196.html