美文网首页
Ajax兼容

Ajax兼容

作者: 聽說_0100 | 来源:发表于2018-11-18 16:30 被阅读0次
function Ajax(type, url, data, success, failed){
    // 创建ajax对象
    let xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }

    type = type.toUpperCase();  //转化为大写
    // 用于清除缓存
    let random = Math.random(); //为了防止浏览器缓存

    if(typeof data == 'object'){
        var str = '';
        for(var key in data){
            str += key+'='+data[key]+'&';
        }
        data = str.replace(/&$/, '');
    }

    if(type == 'GET'){
        if(data){
            xhr.open('GET', url + '?' + data, true);
        } else {
            xhr.open('GET', url + '?t=' + random, true);
        }
        xhr.send(null);

    } else if(type == 'POST'){
        xhr.open('POST', url, true);
        // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(data);
    }

    // 处理返回数据
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if((xhr.status >= 200&&xhr.status<300)||xhr.status==304){
                success(xhr.responseText);
            } else {
                if(failed){
                    failed(xhr.status);
                }
            }
        }
    }
}

相关文章

  • Ajax兼容

  • 原生js ajax网络数据请求 XMLHttprequest、A

    再学封装ajax请求 原生JS,AJAX数据封装 兼容性处理 脚本: 请求操作:

  • JavaScript 原生 AJAX

    JavaScript 原生 ajax 注意浏览器兼容性判断 JQuery 类库的 ajax

  • Ajax Axios

    关于Ajax兼容性问题 前端原生Ajax(get方式),后端使用node.js 前后端代码: 前端原生Ajax(p...

  • iframe实现ajax效果

    iframe实现ajax的效果兼容性效果最好。

  • 自己手写ajax

    1.创建ajax对象 var oAjax = new XMLHttpRequest(); 不兼容 ...

  • ajax兼容方法

    function createXhr() { let xhr = null; if (window.XMLHttp...

  • ajax原生兼容

    总结一下JavaScript原生ajax写法 有get和post两种方法,写法差异不大 POST方法: GET方法

  • AJAX兼容方案

    XMLHttpRequest 在老版本浏览器(IE5/6)中有兼容问题,可以通过另一种方式代替

  • JQuery初探

    jQuery 在兼容性方面做得很好,1.7 版本兼容到 IE 6 jQuery 还有动画、AJAX 等模块,不止 ...

网友评论

      本文标题:Ajax兼容

      本文链接:https://www.haomeiwen.com/subject/qkygfqtx.html