js封装ajax

匿名 (未验证) 提交于 2019-12-02 23:42:01
//封装ajax         function ajax(obj) {             //创建xhr对象;             var xhr = new XMLHttpRequest();             //后面随机数防止浏览器缓存             obj.url = obj.url + "?rand=" + Math.random();             obj.method = obj.method.toUpperCase();             //异步调用             if (obj.async) {                 //监听响应状态                 xhr.onreadystatechange = function() {                     if (xhr.readyState == 4) {                         callback();                     }                 };             }             //启动HTTP请求             xhr.open(obj.method, obj.url, obj.async);             if (obj.method == 'POST') {                 xhr.send(obj.data);             } else {                 xhr.send();             }             //同步调用             if (!obj.async) {                 callback();             }              function callback() {                 try {                     var res = JSON.parse(xhr.response)                 } catch (e) {                     console.error(e)                 }                 if (xhr.status == 200) {                     obj.success && obj.success(res);                 } else {                     obj.error && obj.error(res);                 }             }         }               ajax({                 method: 'post',                 url: 'test.test.test',                 data: formData,                 async: true,                 success: function(res) {                                        },                 error: function(e) {                                   },             }); 

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!