封装原生Ajax
我们常常引用jq就是为了使用上面的ajax,方便又实用。但是jq文件一个高达几十kb,还有近几年jq的发展趋势不容乐观,jq中还迟迟没有改进。于是自己造轮子,下面封装了原生JS ajax 。你可以直接复制拿过来用。
function ajax(obj) { // 对实参处理 obj = obj || {}; // 定义局部变量 var xmlhttp, type, url, async, dataType, data; // 默认type为GET type = obj.type || ‘GET’; type = trim(type).toUpperCase(); // 接口 url = obj.url url = trim(url); // 默认为异步请求 async = obj.async || true; // 设置跨域 dataType = obj.dataType || ‘HTML’; dataType = trim(dataType).toUpperCase(); // 发送参数 data = obj.data || {}; // 删除左右空格 function trim(str) { return str.replace(/^\s+|\s+$/g, “”); }; // 定义格式化参数函数 var formatParams = function () { if (typeof (data) == “object”) { var str = “”; for (var pro in data) { str += pro + “=” + data[pro] + “&”; } data = str.substr(0, str.length - 1); } if (type == ‘GET’ || dataType == ‘JSONP’) { if (url.lastIndexOf(’?’) == -1) { url += ‘?’ + data; } else { url += ‘&’ + data; } } } // 第一步,创建xmlhttprequest对象用来和服务器交换数据。 if (window.XMLHttpRequest) { //Chrome || Firefox xmlhttp = new XMLHttpRequest(); } else { //IE xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”); }
更多请见:https://blog.csdn.net/weixin_44519496/article/details/120127889
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。