Ajax

function json2str(json) {
    // 0.给json添加随机因子
    json.t = Math.random();
    // 1.将json转换为数组
    var arr = [];
    for(var key in json){
        arr.push(key+"="+encodeURIComponent(json[key]));
    }
    // 2.将数组转换为字符串返回
    return arr.join("&");
}

function ajax(type, url, timeout, json, success, error) {
    var str = json2str(json);

    // 1.创建异步对象
    if(window.XMLHttpRequest){
        var xhr = new XMLHttpRequest()
    }else{
        var xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if(type == "get"){
        // 2.设置URL
        xhr.open(type, url+"?"+str);
        // 3.发送请求
        xhr.send();
    }else{
        // 2.设置URL
        xhr.open(type, url);

        // 设置请求头
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        // 3.发送请求
        xhr.send(str);
    }
    // 4.注册事件
    xhr.onreadystatechange = function () {
        // 5.处理返回数据
        // 判断请求状态
        if(xhr.readyState == 4){
            clearTimeout(timer);
            // 判断HTTP状态
            if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                success(xhr.responseText);
            }else{
                error(xhr.status);
            }
        }
    }
    // 6.超时处理
    if(timeout){
        var timer = setTimeout(function () {
            xhr.abort(); // 中断请求
        }, timeout);
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容