【javascript】ajax

XMLHttpRequest

ajax是一种无需刷新页面就可以从服务器获取数据的方法。本质是XMLHttpRequest对象,在不需要兼容IE7以下版本时,可以用以下方法进行声明

    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new AxtiveXObject('Microsoft.XMLHTTP');
    }

方法

  • open()
xhr.open("get", "example.txt", false);

1.get / post
2.请求的URL
3.是否异步

  • send()
xhr.send(null);

1.接收一个参数,即请求主体发送的数据,不需要需要传null
2.send后,请求会被分派到服务器

  • 响应数据
    响应数据自动填充xhr对象

    1. responseText:作为响应主体被返回的文本
    2. responseXML:包含响应的XML DOM文档
    3. status:响应的http状态(一般200为成功,304为读取浏览器缓存)
    4. statusText: http状态说明
  • readyState
    请求响应过程中,当前活动阶段
    【javascript】ajax_第1张图片

只要 readyState 的值发生变化就会触发 readystatechange 事件。我们可以监听readystatechange事件,判断 readyState 为4时执行后续操作,不过必须在调用open()之前指定onreadystatechange()事件处理程序才能保证跨浏览器之间的兼容性。

var xhr = createXHR();
    xhr.onreadystatechange = function(){
        if (xhr.readyState === 4){
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){
                  alert(xhr.responseText);
        } else {
             alert("Request was unsuccessful: " + xhr.status);
        }
} };
xhr.open("get", "example.txt", true);
xhr.send(null);
  • xhr.abort() 可以取消异步请求

ajax的封装

_ajax = function(obj) {
        obj = obj || {};
        obj.type = (obj.type || 'GET').toUpperCase();
        obj.dataType = obj.dataType || 'json';

        var params = _formatParams(obj.data);
        var xhr;

        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new AxtiveXObject('Microsoft.XMLHTTP');
        }
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    obj.success && obj.success(xhr.responseText, xhr.responseXML);
                } else {
                    obj.error && obj.error(xhr.status);
                }
            }
        }

        if (obj.type === 'GET') {
            xhr.open('GET', obj.url + '?' + params, true);
            xhr.send(null);
        } else if (obj.type === 'POST') {
            xhr.open('POST', obj.url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(params);
        }
    };

// 参数格式化
_formatParams = function(data) {
    var arr = [];
    for (var name in data) {
        arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
    }
    // 清除缓存
    arr.push('t=' + Math.random());
    return arr.join('&');
};

// 使用
_ajax({
    url: requestUrl,
    type: 'POST',
    data: {
        msg: ''
    },
    success: function(res) {}
});

你可能感兴趣的:(javascript,ajax,javascript)