原生js封装Ajax
【转载请注明出处】 1 /**
* @fileoverview ajax请求公用组件
* @author Limo
* @date 2015/08/07
* Native package ajax method, make it like the ajax of zepto Lib.
*/
var querystring = require('querystring');
function ajax( opts ) {
// 创建ajax对象
var xhr = null,
abortTimeout = null,
empty =function(){},
ajax_url = "",
opts = {
type : ( opts.type && opts.type.toUpperCase() ) || 'GET',
url : opts.url || "",
data : opts.data || "", //query
dataType : opts.dataType || 'json',
success : opts.success || empty,
error : opts.error || empty,
timeout : opts.timeout || 30000 //默认超时时间:30S ,与产品交互保持一致
}; if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} opts.data = querystring.stringify( opts.data ); if (opts.type == 'GET') {
if(opts.url.indexOf("?")>-1){
if( opts.data =="" ){
ajax_url = opts.url;
} else {
ajax_url = opts.url + '&' + opts.data;
}
} else {
ajax_url = opts.url + '?' + opts.data;
}
xhr.open('GET', ajax_url , true);
41 xhr.send(); } else if (opts.type == 'POST') {
xhr.open('POST', opts.url, true);
// 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send( opts.data );
} // 处理返回数据
51 xhr.onreadystatechange = function () {
/*
** 每当readyState改变时,就会触发onreadystatechange事件
54 ** readyState属性存储有XMLHttpRequest的状态信息
** 0 :请求未初始化
** 1 :服务器连接已建立
** 2 :请求已接受
** 3 : 请求处理中
** 4 :请求已完成,且相应就绪
*/
if (xhr.readyState == 4) {
var res,
error;
xhr.onreadystatechange = empty;
clearTimeout( abortTimeout );
// console.log( "xhr.status: " , xhr.status );
/*
** Http状态码
** 1xx :信息展示
** 2xx :成功
** 3xx :重定向
72 ** 4xx : 客户端错误
73 ** 5xx :服务器端错误
*/
// var protocol = /^([\w-]+:)\/\//.test(opts.url) ? RegExp.$1 : window.location.protocol;
// if ( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:') ) {
if ( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 ) {
res = xhr.responseText; // xhr.responseText 和 xhr.response 结果相同
try {
// console.info( "snsnav request success" );
if( opts.type == 'GET' ){
82 if( opts.dataType == "json" ){
83 res = JSON.parse( xhr.responseText );
} else if ( opts.dataType == 'script' ) {
// http://perfectionkills.com/global-eval-what-are-the-options/
(1,eval)(res);
} else if ( opts.dataType == 'xml' ) {
res = xhr.responseXML;
}
}
// else if( opts.type == 'POST' ){
// }
} catch (e) {
error = e;
}
if( error ){
opts.error( error, 'parsererror' , xhr );
} else {
opts.success( res );
}
} else {
// opts.error( xhr.statusText || 'unknown' , xhr.status ? 'error' : 'abort' , xhr );
103 // xhr.status=0时,相关介绍:http://www.w3.org/TR/XMLHttpRequest/
// The status attribute must return the result of running these steps:
// 1、If the state is UNSENT or OPENED, return 0.
// 2、If the error flag is set, return 0.
// 3、Return the HTTP status code.
// var xhr_status = xhr.status || 'unknown';
opts.error( xhr.statusText || 'unknown' , 'status:'+xhr.status , xhr );
}
// console.log( "xhr.statusText: " , xhr.statusText );
}
}; // function ajaxError( error, type, xhr ){ }
// opts.error( error, 'parsererror',xhr );
// type: "timeout", "error", "abort", "parsererror" if (opts.timeout > 0){ //设置超时时间
abortTimeout = setTimeout(function(){
xhr.onreadystatechange = empty;
//取消当前响应,关闭连接并且结束任何未决的网络活动
xhr.abort(); //请求时间 超过前端设置的超时时间
opts.error('Request.timeout','timeout',xhr);
}, opts.timeout);
128 }
return xhr;
}
module.exports = ajax;
/*
//ajax调用方法:
var ajax = require('../../common/util/ajax.js');
ajax({
url: url,
dataType: 'json',
data : {
'param1' : '111',
'param2' : '222'
},
success: function (result) {
console.log( "result:" , typeof result );
144 //success callback
},
timeout : 30000, //超时时间:30s
error: function ( error, type, xhr ) {
console.error( "error:",error, "type:",type, "xhr:",xhr );
//error callback
}
});
*/
原生js封装Ajax的更多相关文章
- 原生JS封装Ajax插件(同域&&jsonp跨域)
抛出一个问题,其实所谓的熟悉原生JS,怎样的程度才是熟悉呢? 最近都在做原生JS熟悉的练习... 用原生Js封装了一个Ajax插件,引入一般的项目,传传数据,感觉还是可行的...简单说说思路,如有不正 ...
- 使用原生JS封装Ajax
使用原生 的JS封装 Ajax,实现 仿JQuery的Ajax,post,get三种异步请求方式: var MAjax = { //根据浏览器创建异步对象 createXhr: function () ...
- 原生js封装ajax:传json,str,excel文件上传表单提交
由于项目中需要在提交ajax前设置header信息,jquery的ajax实现不了,我们自己封装几个常用的ajax方法. jQuery的ajax普通封装 var ajaxFn = function(u ...
- 原生JS封装ajax方法
http://blog.sucaijiayuan.com/article/89 jquery框架的ajax方法固然好用,但是假如某天我们的项目不能引入jquery或项目需求很简单,没有很多交互功能,只 ...
- 原生js封装ajax,深入理解$.ajax()
直接上代码 //封装的ajax函数 // 传一个对象,所有要用的参数都在对象中 因为不写对象 实参列表个数太多,所以像jq一样,调用ajax也是把对象当实际参数传进去 // type 请求方式 默认g ...
- 原生js封装ajax代码
方法一:(类似jQuery的封装方法) 1.ajax函数封装: /* *author: Ivan *date: 2014.06.01 *参数说明: *opts: {'可选参数'} **method: ...
- ajax 原生js封装ajax [转]
/* 封装ajax函数 * @param {string}opt.type http连接的方式,包括POST和GET两种方式 * @param {string}opt.url 发送请求的url * @ ...
- 原生JS封装ajax以及request
一.封装原生的xhr为ajax类 xhr以及用法见之前的文章 1.根据url确定请求的头部以及别的信息. var _headerConfig = {}; if(url.indexOf('getcapt ...
- 原生js封装ajax,实现跨域请求
描述: 需要ajax跨域请求,用cors跨域方案.服务端设置: header('Access-Control-Allow-Origin: http://front.ls-la.me'); header ...
随机推荐
- [jquery]模仿radio单项选择
今天写了个小功能,模仿radio单选, //单选收货地址 $(".wuliu-table-to").find(".called").click(function ...
- python开发目录合并小工具 PathMerge
前言 这个程序陆陆续续开发了几天,正好我在学Python,就一边做一边学,倒是学到不少东西. 不得不说python是快速开发的好工具. 程序做了一些改进,这两天又忙着毕设,现在才想起来发到博客上.想想 ...
- Python安装包或模块的多种方式汇总
windows下安装python第三方包.模块汇总如下(部分方式同样适用于其他平台): 1. windows下最常见的*.exe,*msi文件,直接运行安装即可: 2. 安装easy_install, ...
- [生活日记]参与unity非游戏行业开发者大会小结
今天下午花了半天时间公司全体都去人民广场参与了一个unity非游戏行业开发者大会,主要了解到unity这款全球顶尖之一的游戏引擎的一个发展史,从05年三个美国人技术研发开始,一直到12年开始引进中国, ...
- UML学习(三)-----序列图
UML的模型中可分为两种,动态模型和静态模型.用例图.类图和对象图都是UML中的静态结构模型.而在UML系统动态模型的其中一种就是交互视图,它描述了执行系统功能的各个角色之间相互传递消息的顺序关系.序 ...
- 11 JSP/EL表达式/EL函数
JSP * 概述: JSP(Java Server Pages)与Java Servlet一样,是在服务器端执行的不同的是先由服务器编译部署成Servlet执行 * JSP的运行原 ...
- 如何转换WMV到MP3,WMV到MP3播放器
非常好的软件!!!!!没有注册,可以用.推荐给大家! http://www.daniusoft.com/cn/convert-wmv/wmv-to-mp3.html http://hi.baidu.c ...
- 图形化查看maven的dependency依赖
开发项目的时候,我们想知道一个maven的依赖库是来自那个工程,eclipse有插件可以直接看Dependency Hierarchy,推荐一个第三方的工具yED 在工程的pom.xml文件中添加如下 ...
- js无参数对象
<script type="text/javascript"> var o={ a : function(){ for (var i = arguments.lengt ...
- Poj2479 & Poj 2593
就是按着DP的思路来做的,结果还是想不到.T_T,行了,别玻璃心了,继续. 这道题目是求在一列数里,由两部分子段和组成的最大和.即对于连续整数组成的串 S1.S2,使 S1 + S2 的和最大. 题目 ...