自用的简单封装ajax,试用初学者
2017-03-22 15:39
239 查看
(function (window) { //避免污染全局变量 function ajax(options) { var init = { type: 'get', url: "", data: {}, async: true, success: function (txt) { }, error: function () { }, cache: true, beforeSend: function () { }, complete: function () { } }; options = merge(init, options); options.data = hb(options.data); var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); //用一个变量来保存是否是post提交方式 值为布尔值 var is_post = /^post$/i.test(options.type); //来判断是否需要处理url get方式的data需要加到url中 if (!is_post) { //没有考虑到url可能已经有参数 //优先级的问题 &的问题 options.url += (options.url.indexOf('?') > -1 ? "&" : '?') + options.data; //处理缓存 是否加上时间戳 options.url += options.cache ? "" : '&__time__=' + new Date().getTime(); } xhr.open(options.type, options.url, options.async); //开始动画 options.beforeSend(); //设置头文件 if (is_post) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); } xhr.send(options.data); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { //提供xhr的使用权限 方便在使用时可以获取xhr的其他属性 options.success(xhr.responseText, xhr); // complete(); } else { options.error(xhr.status, xhr); } options.complete(); } } } function merge(init, add) { for (var key in add) { if (key in init) { init[key] = add[key]; } } return init; } function hb(obj) { var str = ""; for(var key in obj){ str+= key+'='+obj[key]+'&'; } return str; } window.ajax=ajax; })(window);
相关文章推荐
- 自己封装的一个最简单的ajax
- 自己写的封装好的简单的AJAX--javascript (改良版)
- 封装自用的脚本ajax.js
- html ajax 简单封装
- 《php---ajax简单示例---jquery内部运行原理》---jquery只是就ajax的一些功能进行了封装
- ajax简单封装
- ajax代码及简单封装
- 简单的Ajax封装
- 一个简单的ajax封装
- 自己写的封装好的简单的AJAX--javascript (改良版)
- ajax的简单封装
- 一个简单的ajax封装
- ajax简单封装
- ajax简单的封装一下
- [已封装] DIV拖动类 支持在FF下拖动,调用简单 主要代码都有注释 适合初学者学习
- 简单封装了下基本的AJAX实现
- 最简单的asp.net ajax post,适用于初学者.
- Ajax代码简单封装。
- Extjs读取更改或者发送ajax返回请求的结果简单封装
- 自己写的封装好的简单的AJAX--javascript