原生JS创建ajax请求

近一个月面试,有两家笔试题都让写原生ajax

在此做一下笔记,w3school官网讲的超级清楚 明白 又 简单易懂,建议看w3school

get请求

 1 function ajaxGet(url) {
 2     //三元表达式
 3     //所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。
 4     //IE5 和 IE6 使用 ActiveXObject
 5     var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
 6     
 7     //每当 readyState 改变时,就会触发 onreadystatechange 事件。
 8     //readyState 属性存有 XMLHttpRequest 的状态信息。
//readyState有0-4五个值:
//0:初始化状态。XMLHttpRequest对象已创建或已被abort()方法重置。
    //1:open()方法已调用,但是send()方法未调用。请求还没有被发送。
    //2:Send() 方法已调用,HTTP 请求已发送到 Web 服务器。未接收到响应。
    //3:所有响应头部都已经接收到。响应体开始接收但未完成。
    //4:HTTP 响应已经完全接收。
 9     xmlHttp.onreadystatechange = function() {
10         if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
11             console.log("请求发送成功!");
12         }
13         else {
14             console.group("请求发送失败!");
15             console.log("XMLHttpRequest 的状态:"+xmlHttp.readyState);
16             console.log("服务器响应状态:"+xmlHttp.status);
17             console.groupEnd();
18         }
19     }
20 
21     //发送set请求
22     xmlHttp.open("GET",url,true);
23     xmlHttp.send();
24 }

 post请求

 1 function ajaxPost(url,data){
 2     var xmlHttp = window.XMLHttpRequest : new XMLHttpRequest() ? new ActiveXObject("Microsoft.XMLHTTP");
 3     xmlHttp.onreadystatechange = function() {
 4         if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
 5             console.log("POST请求发送成功");
 6         }
 7         else {
 8             console.group("请求发送失败!");
 9             console.log("XMLHttpRequest的状态:"+xmlHttp.readyState);
10             console.log("服务器响应状态:"+xmlHttp.status);
11             console.groupEnd();
12         }
13     }
14     xmlHttp.open("POST","文件在服务器上的位置或者请求的URL","同步请求/异步请求 false/true");
15     xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//使用setRequestHeader来添加HTTP头
16     xmlHttp.send(data);
17 }                

 

posted @ 2018-08-20 15:59  飓风狗腿子  阅读(184)  评论(0编辑  收藏  举报