原生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 ...
随机推荐
- 开发微信App支付
1.首先到官方下载Demo,地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1 下载后的目录结构如下:
- 【Java EE 学习 32 下】【JQuery】【JQuey中的DOM操作】
一.JQuery中的DOM操作. 什么是DOM:DOM是一中和浏览器.平台.语言无关的接口,使用该接口可以轻松访问页面中所有的标准组件.DOM简称文档对象模型,是Document Oject Mode ...
- 在ASP.NET MVC项目中使用React
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:最近在开发钉钉的微应用,考虑到性能和UI库的支持,遂采用了React来开发前端. 目前 ...
- 13.linux中断处理程序
linux中断处理程序 一.中断处理流程 在linux内核代码中进入entry-armv.S目录: linux统一的入口:__irq svc. 进入了统一的入口之后,程序跳到irq_handler标号 ...
- 注解:【无连接表的】Hibernate双向1->N关联
Person与Address关联:双向1->N,[无连接表的],推荐使用 #由N端控制关联关系 #对于指定了mappedBy属性的@OneToMany,@ManyToMany,@OneToOne ...
- [C++][数据结构]栈(stack)的实现
对于栈的定义,前人之述备矣. 我实现的是一个stack<value>容器类,支持push,pop,top,size,empty,clear和copy construction操作. 主要的 ...
- 常见开发需求之js处理url汉字编码中的乱码
需求及解决 两个页面传值的需求是很常见的,angular中有很多常见的方法用于传值,而且都不会受到字符编码的影响,而采用传统的url中拼字符串进行传值的操作,如果拼串中涉及到中文字符,我们就要考 ...
- http返回码301、302、307、305含义和区别
301永久重定向,302暂时移动,seo对301和302的处理不一样: 301和302会出现数据丢失问题,重定向后请求数据丢失: 307临时重定向,数据不会丢失:
- Angular JS 学习之路由
1.AngularJS路由允许我们通过不同的URL访问不同的内容:通过AngularJS可以实现多视图的单页WEB访问(SPA) 2.通常我们的URL形式为http://runoob.com/firs ...
- Delphi中滚动文字的应用
1.添加一个Timer控件,Interval属性设置为20. 2.添加一个Label控件,Name为labMessage. 3.在Timer的OnTimer事件添加如下代码: procedure TF ...