原生的js实现ajax请求

来源:互联网 发布:如何注册淘宝帐号 编辑:程序博客网 时间:2024/05/22 17:30

1、get和post请求

function getXMLHttpRequest() {    var xhr;    if(window.ActiveXObject) {      xhr = new ActiveXObject("Microsoft.XMLHTTP");    }else if (window.XMLHttpRequest) {      xhr = new XMLHttpRequest();    }else {      xhr = null;    }    return xhr;  }    /**data = 'id=1122&name="liyongfen"'*/function ajax(method,url,data,callback) {    var xhr = getXMLHttpRequest();   if(method == 'post' || method == 'POST'){    xhr.open(method,url,true);    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');     xhr.send(data);    }else if(method == 'get' || method == 'GET'){     xhr.open(method,url + '?' + data,true);     xhr.send();   }    xhr.onreadystatechange = function() {      if(xhr.readyState == 4 && xhr.status == 200) {        callback(xhr.responseText);      }    }} 

注释:get请求与post的区别,get将参数放入url中发送。post需要设置请求头部,将发送的数据data放入xhr.send(data);中。

原创粉丝点击