ajaxシンプルパッケージ

ajaxシンプルパッケージ

function ajax(options) {
    
    
    // 该对象存储的是默认值
    let defaults = {
    
    
            type: 'get',
            url: '',
            header: {
    
    
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
    
    },
            success: function() {
    
    },
            error: function() {
    
    }
        }
        // 用options中的属性替换defaults中的属性
    Object.assign(defaults, options);
    const xhr = new XMLHttpRequest();
    // 拼接请求参数的变量(get)
    let params = '';
    for (const key in defaults.data) {
    
    
        params += key + '=' + defaults.data[key] + '&';
    }
    // 删掉最后一个'&'
    params = params.substring(0, params.length - 1);

    // 判断请求方法 get/post
    // get==>把params加在url后面
    if (defaults.type === 'get') {
    
    
        defaults.url = defaults.url + '?' + params;
    }
    // 配置ajax对象(初始化)
    xhr.open(defaults.type, defaults.url);
    // 发送请求
    if (defaults.type === 'post') {
    
    
        // 请求参数类型
        let contentType = defaults.header['Content-Type'];
        xhr.setRequestHeader('Content-Type', contentType);
        if (contentType === 'application/json') {
    
    
            xhr.send(JSON.stringify(defaults.data));
        } else {
    
    
            xhr.send(params);
        }
    } else {
    
    
        xhr.send();
    }

    // onload
    xhr.onload = function() {
    
    
        // 获取响应头中的数据,判断返回的是字符串还是对象
        const contentType = xhr.getResponseHeader('Content-Type');

        let responseText = xhr.responseText;
        // 若该字段包含application/json,则服务器返回的是json对象
        if (contentType.includes('application/json')) {
    
    
            responseText = JSON.parse(responseText);
        }
        // 判断成功还是失败
        if (xhr.status === 200) {
    
    
            defaults.success(responseText, xhr);
        } else {
    
    
            defaults.error(responseText, xhr);
        }
    }
    // 处理超时
    xhr.onerror = function(err) {
    
    
		console.log(err);
	}
}

おすすめ

転載: blog.csdn.net/wdhxs/article/details/111476495