非常简单的原生AJAX的封装+请求案例+xhr level2中的超时控制及兼容性写法
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
// 封装AJAX请求函数
function ajax(url, method, data, timeout, successCallback, errorCallback) {
    // 创建XMLHttpRequest对象
    var xhr = new XMLHttpRequest();
 
    // 设置请求方法和URL
    xhr.open(method, url, true);
 
    // 设置超时时间
    if (timeout) {
        xhr.timeout = timeout;
        xhr.ontimeout = function() {
            errorCallback('请求超时');
        };
    }
 
    // 发送请求
    xhr.send(data);
 
    // 监听请求完成
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                successCallback(xhr.responseText);
            } else {
                errorCallback('请求失败,HTTP 状态码: ' + xhr.status);
            }
        }
    };
 
    // 监听错误
    xhr.onerror = function() {
        errorCallback('网络错误');
    };
}
 
// 使用封装后的函数发起GET请求
ajax('https://api.example.com/data', 'GET', null, 10000, function(response) {
    console.log('请求成功:', response);
}, function(error) {
    console.error('请求失败:', error);
});这段代码展示了如何封装一个简单的AJAX请求函数,并在其中包含了超时处理和错误处理。函数参数包括请求的URL、请求方法、发送的数据、超时时间、成功回调和错误回调。函数内部创建了XMLHttpRequest对象,设置了请求参数,发送请求,并监听了请求的不同状态变化。这是一个很好的学习示例,适合初学者理解AJAX请求的基本过程。
评论已关闭