用原生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
上一篇: js中递归函数的经典案例
下一篇: 解决粘包问题