欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用原生js-对ajax封装

程序员文章站 2022-09-14 10:34:50
function ajax(methods, url, callback, params) { //1.创建对象 var xhr = new XMLHttpRequest(); //2.告诉ajax请求地址以及请求方式 //参数提交方式为get且参数不为空,进行get方式参数传递 methods == 'GET' || methods == 'get' && params != undefined ? xhr.open(methods, url +...
function ajax(methods, url, callback, params) {
    //1.创建对象
    var xhr = new XMLHttpRequest();

    //2.告诉ajax请求地址以及请求方式
    //参数提交方式为get且参数不为空,进行get方式参数传递
    methods == 'GET' || methods == 'get' && params != undefined ? xhr.open(methods, url + '?' + params, true) : xhr.open(methods, url, true);

    //3.监听状态改变事件
    xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            //当服务器响应数据完成和响应数据正确才执行回调函数,进行参数传递
            //5.获取服务器数据
            callback(this.responseText);
        }
    };

    //4.发生请求
    //参数提交方式为post且参数不为空,进行post方式参数传递
    methods == 'POST' || methods == 'post' && params != undefined ? xhr.send(params) : xhr.send(null);
}

本文地址:https://blog.csdn.net/weixin_45792953/article/details/107285563