原生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 ...
随机推荐
- 伪随机数(线性同余法)C语言
/**Keil Lib*2015.6.12*Pass*by lort*/uint32 Srandx ; uint32 SrandK = 1103515245;//0x41C64E6D;uint32 S ...
- 开发ios的语言
iOS发展这么多年了,很多第三方语言都向开发一种自己的iOS,于是多种跨平台诞生了! Object-c.swift: 当然是开发iOS的首先,毕竟是苹果自己的东西,也是最流行.最适合开发ios的,无论 ...
- istringstream、ostringstream、stringstream 类简介
本文系转载,原文链接:http://www.cnblogs.com/gamesky/archive/2013/01/09/2852356.html ,如有侵权,请联系我:534624117@qq.co ...
- LeetCode之171. Excel Sheet Column Number
---------------------------------- 乘权相加即可. AC代码:(从右往左) public class Solution { public int titleToNum ...
- ORACLE用户创建&删除
●sqlplus登陆sqlplus sys/isc@testgmmc as sysdba●创建用户create user testpoi3 IDENTIFIED by iscaccount unloc ...
- Win7+Ubuntu双系统安装完成后时间不一致相差大概8小时
Win7+Ubuntu双系统时间不一致 解决方法: 第一种在Windows下进行如下修改: 在 注册表项:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Con ...
- Logging vs NoLogging
You Asked My Prod environments is like this. Three Node RAC, Active Data guard enabled. There is a p ...
- CozyRSS开发记录2-酷炫的皮肤库
CozyRSS开发记录2-酷炫的皮肤库 1.MaterialDesignToolkit 最开始微软推出Metro设计风格的时候,有人喜欢有人喷.紧接着,Ios也开始做扁平化的UI,这时候,扁平化已成为 ...
- 分享一下自己用c++写的小地图
http://www.unrealchina.com/forum.php?mod=viewthread&tid=451&extra=&from=portal&page= ...
- Queue 的用法
对Queue 进队出队的使用不是很了解,刷题时想要直接用,所以查了一下.平时用的话用add 和remove 即可. Queue<E> 是接口. LinkedList 实现了Queue接口, ...