<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width, initial-scale=1.0"> <Meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ajax封装</title> </head> <body> <input type="button" value="按钮1" id="btn1"> <input type="button" value="按钮2" id="btn2"> <input type="button" value="按钮3" id="btn3"> </body> <script> var ajax = { getxhr: function () { return new XMLHttpRequest(); }, get: function (url, sync = true,fun) { var xhr = this.getxhr(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { fun(xhr.responseText); } } xhr.open('get', url, sync); xhr.send(); }, post: function (url, post_data, sync = true,fun) { var xhr = this.getxhr(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { fun(xhr.responseText); } } xhr.open('post', url, sync); xhr.send(post_data); } } document.getElementById('btn1').onclick = function(){ ajax.get('http://127.0.0.1:8080/gets',true,function(data){ alert(data); }); ajax.post('http://127.0.0.1:8080','name=lisi',true,function(data){ alert(data); }) } </script> </html>
(function () { var ajax = { getxhr: function () { return new XMLHttpRequest(); }, get: function (url, fun, sync = true) { // 调用对象中的方法获取xhr对象 var xhr = this.getxhr(); // 设置状态码改变事件 xhr.onreadystatechange = function () { // 状态码为4 说明服务器返回结束 客户端接收到全部数据 if (xhr.readyState == 4) { fun(xhr.responseText); } } xhr.open('get', url, sync); xhr.send(); }, post: function (url, post_data, sync = true, fun) { var xhr = this.getxhr(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { fun(xhr.responseText); } } xhr.open('post', url, sync); xhr.send(post_data); } } // 封装时将封装内容给window对象 // 不要和现有window对象中的属性重名 window.myajax = ajax; })()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。