听说面试题会问这个,于是搜了一下,拿了个简易版。简单版本varrequest=newXMLHttpRequest();request.open("GET","/a/b/c?name=ff",true);request.onreadystatechange=function(){if(request.readyState===4&&request.status===200){console.log(request.responseText);}};request.send();更细化varrequest=newXMLHttpRequest();request.open("GET","/a/b/c?name=ff",true);request.onload=()=>console.log(request.responseText);request.send();再次查看详细版本。这里我就按照我个人写代码的方式总结一下。(IE低版本不考虑)图LRA[创建异步对象]-->BB[设置请求地址]-->CC[发送请求]-->DD[监听状态]-->EE[处理结果]5步,然后开始写代码。varxmlhttp=newXMLHttpRequest();method是一个url,在GET/POST中是请求的地址第三个参数是async一个可选的布尔型参数,表示是否异步执行操作,默认为true。xmlhttp.open(method,url,true)需要区分method处理方法不一样。if(method.trim().toUpperCase()==="GET"){xmlhttp.send(null);}elseif(method.trim().toUpperCase()==="POST"){xmlhttp.setRequestHeader("内容类型","application/x-www-form-urlencoded");xmlhttp.send(dataToString(data));}监听和处理都放在一起xmlhttp.onreadystatechange=function(){clearTimeout(timer);如果(xmlhttp.readyState===4){如果((xmlhttp.status>=200&&xmlhttp.status<300)||xmlhttp.status===304){成功(xmlhttp);//成功后回调;}else{错误(xmlhttp);//失败后回调;}}}说实话,拆开看我也是一头雾水。..完整代码如下。functionmyAjax({method,url,data,timeout,success,error}={}){//处理数据functiondataToString(data){data.t=newDate().getTime();变量res=[];for(varkeyindata){//需要将key和value转换成非中文形式,因为url不能有中文。使用encodeURIComponent();res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));}返回res.join("&");}//1.创建一个对象。varxmlhttp=newXMLHttpRequest();//2.设置请求地址xmlhttp.open(method,url);//3.发送请求if(method.trim().toUpperCase()==="GET"){xmlhttp.send(null);}elseif(method.trim().toUpperCase()==="POST"){//POST需要设置headerxmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send(dataToString(data));}//4.监听状态变化的回调函数xmlhttp.onreadystatechange=function(){clearTimeout(timer);if(xmlhttp.readyState===4){if((xmlhttp.status>=200&&xmlhttp.status<300)||xmlhttp.status===304){//5.回调成功(xmlhttp);}else{//5.失败后的回调error(xmlhttp);}}};//判断外界是否超过超时时间if(option.timeout){timer=setInterval(function(){xmlhttp.abort();//中止请求clearInterval(timer);},timeout);}}
