【转载请注明出处】
1 /**
2 * @fileoverview ajax请求公用组件
3 * @author Limo
4 * @date 2015/08/07
5 * Native package ajax method, make it like the ajax of zepto Lib.
6 */
7 var querystring = require('querystring');
8 function ajax( opts ) {
9 // 创建ajax对象
10 var xhr = null,
11 abortTimeout = null,
12 empty =function(){},
13 ajax_url = "",
14 opts = {
15 type : ( opts.type && opts.type.toUpperCase() ) || 'GET',
16 url : opts.url || "",
17 data : opts.data || "", //query
18 dataType : opts.dataType || 'json',
19 success : opts.success || empty,
20 error : opts.error || empty,
21 timeout : opts.timeout || 30000 //默认超时时间:30S ,与产品交互保持一致
22 };
23
24 if (window.XMLHttpRequest) {
25 xhr = new XMLHttpRequest();
26 }
27
28 opts.data = querystring.stringify( opts.data );
29
30 if (opts.type == 'GET') {
31 if(opts.url.indexOf("?")>-1){
32 if( opts.data =="" ){
33 ajax_url = opts.url;
34 } else {
35 ajax_url = opts.url + '&' + opts.data;
36 }
37 } else {
38 ajax_url = opts.url + '?' + opts.data;
39 }
40 xhr.open('GET', ajax_url , true);
41 xhr.send();
42
43 } else if (opts.type == 'POST') {
44 xhr.open('POST', opts.url, true);
45 // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
46 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
47 xhr.send( opts.data );
48 }
49
50 // 处理返回数据
51 xhr.onreadystatechange = function () {
52 /*
53 ** 每当readyState改变时,就会触发onreadystatechange事件
54 ** readyState属性存储有XMLHttpRequest的状态信息
55 ** 0 :请求未初始化
56 ** 1 :服务器连接已建立
57 ** 2 :请求已接受
58 ** 3 : 请求处理中
59 ** 4 :请求已完成,且相应就绪
60 */
61 if (xhr.readyState == 4) {
62 var res,
63 error;
64 xhr.onreadystatechange = empty;
65 clearTimeout( abortTimeout );
66 // console.log( "xhr.status: " , xhr.status );
67 /*
68 ** Http状态码
69 ** 1xx :信息展示
70 ** 2xx :成功
71 ** 3xx :重定向
72 ** 4xx : 客户端错误
73 ** 5xx :服务器端错误
74 */
75 // var protocol = /^([\w-]+:)\/\//.test(opts.url) ? RegExp.$1 : window.location.protocol;
76 // if ( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:') ) {
77 if ( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 ) {
78 res = xhr.responseText; // xhr.responseText 和 xhr.response 结果相同
79 try {
80 // console.info( "snsnav request success" );
81 if( opts.type == 'GET' ){
82 if( opts.dataType == "json" ){
83 res = JSON.parse( xhr.responseText );
84 } else if ( opts.dataType == 'script' ) {
85 // http://perfectionkills.com/global-eval-what-are-the-options/
86 (1,eval)(res);
87 } else if ( opts.dataType == 'xml' ) {
88 res = xhr.responseXML;
89 }
90 }
91 // else if( opts.type == 'POST' ){
92 // }
93 } catch (e) {
94 error = e;
95 }
96 if( error ){
97 opts.error( error, 'parsererror' , xhr );
98 } else {
99 opts.success( res );
100 }
101 } else {
102 // opts.error( xhr.statusText || 'unknown' , xhr.status ? 'error' : 'abort' , xhr );
103 // xhr.status=0时,相关介绍:http://www.w3.org/TR/XMLHttpRequest/
104 // The status attribute must return the result of running these steps:
105 // 1、If the state is UNSENT or OPENED, return 0.
106 // 2、If the error flag is set, return 0.
107 // 3、Return the HTTP status code.
108 // var xhr_status = xhr.status || 'unknown';
109 opts.error( xhr.statusText || 'unknown' , 'status:'+xhr.status , xhr );
110 }
111 // console.log( "xhr.statusText: " , xhr.statusText );
112 }
113 };
114
115 // function ajaxError( error, type, xhr ){ }
116 // opts.error( error, 'parsererror',xhr );
117 // type: "timeout", "error", "abort", "parsererror"
118
119 if (opts.timeout > 0){ //设置超时时间
120 abortTimeout = setTimeout(function(){
121 xhr.onreadystatechange = empty;
122 //取消当前响应,关闭连接并且结束任何未决的网络活动
123 xhr.abort();
124
125 //请求时间 超过前端设置的超时时间
126 opts.error('Request.timeout','timeout',xhr);
127 }, opts.timeout);
128 }
129 return xhr;
130 }
131 module.exports = ajax;
132 /*
133 //ajax调用方法:
134 var ajax = require('../../common/util/ajax.js');
135 ajax({
136 url: url,
137 dataType: 'json',
138 data : {
139 'param1' : '111',
140 'param2' : '222'
141 },
142 success: function (result) {
143 console.log( "result:" , typeof result );
144 //success callback
145 },
146 timeout : 30000, //超时时间:30s
147 error: function ( error, type, xhr ) {
148 console.error( "error:",error, "type:",type, "xhr:",xhr );
149 //error callback
150 }
151 });
152 */