原生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 ...
随机推荐
- Memcache之telnet操作
在telnet Memcache之前,先要确认 memcached已启用. 如:ps -ef |grep memcache netstat -elp |grep memcache 或者 netstat ...
- iOS之自定义控件
一.使用纯代码方式 initWithFrame:中添加子控件 layoutSubViews中设置子控件的fame 对外设置数据接口,重写setter方法给子控件设置数据显示 在的viewControl ...
- Sublime Text 2报“Decode error - output not utf-8”错误的解决办法
[Decode error - output not utf-8] [Decode error - output not utf-8] 应该怎么办? 这是因为python配置的编译环境的编码不 ...
- 根据字体计算CGRect
UILabel *label = [[UILabel alloc]init]; label.numberOfLines = ;//多行显示 label.backgroundColor = [UICol ...
- LockSupport
LockSupport是高级线程同步类的基础,用来block和释放线程.这里要区别notify和wait的点在于这里可以先unpark,再park.(有点类似于unpark等于-1,park等于+1. ...
- MIME列表
.asx,video/x-ms-asf.xml,text/xml.tsv,text/tab-separated-values.ra,audio/x-pn-realaudio.sv4crc,applic ...
- SimpleDateFomat里面的parse方法的使用
parse方法用于将字符串类型的日期/时间解析为Date类型.语法 public Date parse(参数) 要加上这句 throws ParseException或者:try{}catch(){} ...
- outerHTML
1,获取html结构:当前节点下的代码: jQuery.html() 是获取当前节点下的html代码,并不包含当前节点本身的代码: 2,jQuery.prop("outerHTML" ...
- winform对话框控件、打印控件
对话框控件: ColorDialog:颜色选择对话框,让用户自行选择一种颜色,使用方法类似FontDialog FontDialog:字体选择对话框,让用户自行选择一种字体(也可以选择字体颜色,需要在 ...
- self.automaticallyAdjustsScrollViewInsets
导航视图内Push进来的以“TableView”(没有ScrollView截图,就将就一下)为主View的视图,本来我们的cell是放在(0,0)的位置上的,但是考虑到导航栏.状态栏会挡住后面的主视图 ...