封装的原生ajax
2016-09-18 14:18
183 查看
1.根据不同的浏览器 创建XMLHttpResponse对象
2.准备发送的相关参数 1发送方式(get/post) 2发送地址url(当get请求时,url包含相关的参数) 3同步异步方式
3.send发送的内容 (get发送send为null post发送时要设置请求头,及请求主题)
4.回调函数的设置(onreadystatechange / readystate / status)判断文件类型(xml/text)
<body> <script type="text/javascript"> <!-- data = { data: "", dataType: "xml/jsop", type: "get/post", url: "", asyn: "true/false", success: function () { }, failure: function () { } }--> <!--封装的ajax--> function ajax(data) { //1.创建xhr对象\ var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // 准备发送前的一些配置参数 var type = data.type == 'get' ? 'get' : 'post'; var url = ''; if (data.url) { url = data.url; if (type == 'get') { url += "?" + data.data + "&_t=" + new Date().getTime(); alert(data.data); } } var flag = data.async == 'true' ? 'true' : 'false'; xhr.open(type, url, flag); //3.send if (type == 'get') { xhr.send(null); } else if (type == 'post') { xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.send(data.data); } // 4.回调函数 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (typeof data.success == 'function') { var d = data.dataType == 'xml' ? xhr.responseXML : xhr.responseText; data.success(d); } else { if (typeof data.failure == 'function') { data.failure(); } } } } } //ajax封装函数的使用 window.onload原生的javascript使用 window.onload = function () { var btn = document.getElementById('btn'); btn.onclick = function () { var param = { url: "ajaxJsp.jsp", type: 'get', dataType: 'json', success: function (data) { alert(data); } }; ajax(param); } } </script> <div id="ems"> <div> <input type="text" id="code"> <input type="button" value="查询" id="btn"> </div> <div id="list"></div> </div> </body>
相关文章推荐
- 原生JS封装ajax 传json,str,excel文件上传提交表单(推荐)
- 使用原生js封装的ajax(兼容jsonp)
- 原生AJAX封装的简单实现
- javascript - 封装原生js实现ajax
- js 封装原生ajax
- 用原生JS对AJAX做简单封装的实例代码
- 【转】封装原生JS实现Ajax
- 原生js实现对Ajax的封装(仿jquery)
- 原生js封装ajax代码
- ajax和jsonp的原生封装
- 原生JS封装AJAX请求
- 原生JS封装Ajax插件(同域&&jsonp跨域)
- 原生js封装的ajax方法示例
- 现在还在学习中,试着重新做了一个AJAX原生的封装
- 理解ajax技术,封装原生 ajax请求
- js原生创建封装ajax的方法,附XMLHttpRequest状态码
- 原生Ajax的多种简单封装
- 原生AJAX的封装
- 原生JavaScript封装ajax
- 封装原生ajax