Ajax

2017-05-19  本文已影响0人  秒签T
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);
    }

}
上一篇下一篇

猜你喜欢

热点阅读