AdolphYang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

最简单的封装的AJAX:

function myajax(url,onsuccess,fail){
    //确定是否支持xhr
    var xhr = new XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
    //准备发送post异步请求
    xhr.open('POST', url, true);
    //监听并获得返回结果
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) { //4 表示执行完
            if (xhr.status == 200) { //200 表示执行成功
                onsuccess(xhr.responseText);
            } else {
                if (fail) { //有传fail才传出失败信息
                    fail(xhr.status);
                }
            }
        }
    }
    //发送请求
    xhr.send();
}
myajax.js

可以把json字符串转JavaScript对象的AJAX

function myajaxjson(url, onsuccess, fail) {
    //确定是否支持xhr
    var xhr = new XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
    //准备发送post异步请求
    xhr.open('POST', url, true);
    //监听并获得返回结果
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) { //4 表示执行完
            if (xhr.status == 200) { //200 表示执行成功
                if (xhr.getResponseHeader('Content-Type').indexOf('application/json') >= 0) { //响应头中'Content-Type是application/json,则把json字符串转js对象
                    var jsObj = eval('(' + xhr.responseText + ')');
                    onsuccess(jsObj);
                } else {
                    onsuccess(xhr.responseText);
                }
            } else {
                if (fail) { //有传fail才传出失败信息
                    fail(xhr.status);
                }
            }
        }
    }
    //发送请求
    xhr.send();
}
myajaxjson.js

 

posted on 2015-09-12 17:24  AdolphYang  阅读(283)  评论(0编辑  收藏  举报