js封装ajax
来源:互联网 发布:硬件温度监控软件 编辑:程序博客网 时间:2024/06/05 16:41
主要代码
用了两种方式封装,回调函数和Promise,实现都比较简单,太复杂了暂时还写不出来,知识储备还不够~~请看代码:
/*回调函数解决方法*/const ajax = ( url,options={} ) => { const { data = {}, type = 'GET', success, async = true, } = options; var xmlhttp = null; var sendData = []; if( window.XMLHttpRequest ) { xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //对发送数据作处理 if( data != {} ){ for(let key in data){ sendData.push(key + '=' + data[key]); } sendData = sendData.join('&'); } //两种不同请求方式 if(type == 'GET') { url += '?' + sendData; xmlhttp.open( 'GET', url, async ); xmlhttp.send(); } if( type == 'POST' ){ xmlhttp.open( 'POST', url, async); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded") xmlhttp.send( sendData ); } //添加回调函数 xmlhttp.onreadystatechange = () => { if( xmlhttp.readyState == 4) { if( xmlhttp.status == 200 ){ success(xmlhttp.responseText); }else{ console.log("请求失败"); } } }}//promise方式/*const ajax = ( url,options={} ) => { const { data = {}, type = 'GET', async = true, } = options; var xmlhttp = null; var sendData = []; if( window.XMLHttpRequest ) { xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //对发送数据作处理 if( data != {} ){ for(let key in data){ sendData.push(key + '=' + data[key]); } sendData = sendData.join('&'); } //两种不同请求方式 if(type == 'GET') { url += '?' + sendData; xmlhttp.open( 'GET', url, true ); xmlhttp.send(); } if( type == 'POST' ){ xmlhttp.open( 'POST', url, true ); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded") xmlhttp.send( sendData ); } //返回Promise实例 return new Promise( ( resolve, reject ) => { xmlhttp.onreadystatechange = () => { if( xmlhttp.readyState == 4 ) { if( xmlhttp.status == 200 ){ resolve(xmlhttp.responseText); }else{ let json = {readyState:xmlhttp.readyState,status:xmlhttp.status}; reject(json) } } } } )}*/
如果发现错误请告诉我~~还在学习中
阅读全文
1 0
- Ajax的js封装
- 原生js封装Ajax
- js 封装ajax
- js 封装ajax
- js封装ajax函数
- js封装ajax
- js封装ajax方法
- 原生js封装ajax
- 原生JS封装Ajax
- JS-封装 ajax XmlHttpRequest
- js封装ajax
- js封装ajax请求
- 原生JS封装ajax()
- 纯JS封装Ajax对象
- 纯JS封装Ajax对象
- jQuery Ajax通用js封装
- jQuery Ajax通用js封装
- js简单封装ajax场景
- Java泛型参数T详解
- 125. Valid Palindrome
- HDU5521 Meeting
- Codeforces 861 C. Did you mean... (模拟)
- 关于priority_queue的博客传送门
- js封装ajax
- Linux Mint 18 系统安装常见问题整理
- 若容器中包含了new创建的指针,一定要在析构前delete掉
- Machine learning for OpenCV 学习笔记 day6
- makefile命令
- 直流电机控制
- SQL实战题目(三)
- 文章标题 实验三:内部模块化的命令行菜单小程序V2.0
- 关于js中的this的指向问题