微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

自定义ajax

 

现在很少用自定义的ajax了,备份一下

 

function ajax(options) {
    //创建一个ajax对象
    var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft,XMLHTTP");
    //数据的处理 {a:1,b:2} a=1&b=2;
    var str = "";
    for (var key in options.data) {
        str += "&" + key + "=" + options.data[key];
    }
    str = str.slice(1)
        if (options.type == "get") {
            var url = options.url + "?" + str;
            xhr.open("get",url);
            xhr.send();
        } else if (options.type == "post") {
            xhr.open("post",options.url);
            xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
            xhr.send(str)
        }
        //监听
        xhr.onreadystatechange = function () {
        //当请求成功的时候
        if (xhr.readyState == 4 && xhr.status == 200) {
            var d = xhr.responseText;
            //将请求的数据传递给成功回调函数
            options.success && options.success(d)
        } else if (xhr.status != 200) {
            //当失败的时候将服务器的状态传递给失败的回调函数
            options.error && options.error(xhr.status);
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐