现在的项目中都在用VUE 以及react 等MVC, MVVM 框架。 丢弃了原始的JQ 。不可能为了个$.ajax();而把JQ引进来吧。
在vue1的开发中 提供了 vueResouce, vue2 出来后明确提出了不在更新vueResouce 而提供axios 的方法。
在react 的开发中提供fetch 封装的方法。等等。但在工作与后台的交互中基本都是form表单的形式。于是自己封装了个
POST,GET,DELETE 的请求方式。当然根据不同的公司,不同的方式。都可以自己扩展。目前这个只是针对自己所在公司而已。
function api(url,opt,methods) {
return new Promise(function(resove,reject){
methods = methods || 'POST';
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
};
var params = [];
for (var key in opt){
if(!!opt[key] || opt[key] === 0){
params.push(key + '=' + opt[key]);
}
};
var postData = params.join('&');
if (methods.toUpperCase() === 'POST') {
xmlHttp.open('POST', url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
}else if (methods.toUpperCase() === 'GET') {
xmlHttp.open('GET', url + '?' + postData, true);
xmlHttp.send(null);
}else if(methods.toUpperCase() === 'DELETE'){
xmlHttp.open('DELETE', url + '?' + postData, true);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
resove(JSON.parse(xmlHttp.responseText));
}
};
});
}
export default api;
以上这篇原生js 封装get ,post, delete 请求的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。