首页 > 代码库 > js原生ajax请求get post笔记

js原生ajax请求get post笔记

开拓新领域,贵在记录。下面记录了使用ajax请求的get、post示例代码

//ajax get 请求获取数据支持同步异步    var ajaxGet = function (reqUrl, params, callback, async) {        var xhr = null;        if(window.XMLHttpRequest) {            xhr = new XMLHttpRequest();        } else if(window.ActiveXObject) {            xhr = new ActiveXObject("Microsoft.XMLHTTP");        }        if(!xhr) { return false;}        if (async && callback) {            xhr.addEventListener(‘readystatechange‘, function () {                if (xhr.readyState === 4 && xhr.status === 200) {                    callback(xhr.responseText);                }            });        }        reqUrl = reqUrl + (params ? ‘?‘ + params : ‘‘);        params = null;        xhr.open(‘get‘, reqUrl, async);        xhr.send(params);        if (!async) {            return xhr.responseText;        }    };    //ajax post请求获取接口数据    var ajaxPost = function (reqUrl, params, callback, async) {        var xhr = null;        if(window.XMLHttpRequest) {            xhr = new XMLHttpRequest();        } else if(window.ActiveXObject) {            xhr = new ActiveXObject("Microsoft.XMLHTTP");        }        if(!xhr) { return false;}        if (async && callback) {            xhr.addEventListener(‘readystatechange‘, function () {                if (xhr.readyState === 4 && xhr.status === 200) {                    callback(xhr.responseText);                }            });        }        xhr.open(‘post‘, reqUrl, async);        xhr.setRequestHeader(‘Content-type‘, ‘application/x-www-form-urlencoded‘);        var strArr = [];        for(var k in params) {            strArr.push(k + "=" + params[k]);        }        var data = http://www.mamicode.com/strArr.join("&");        xhr.send(data);        if (!async) {            return xhr.responseText;        }    };

 

js原生ajax请求get post笔记