Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function wxRequest(options, callback) {
- var xhr, timer;
- var timedout = false;
- var abortReq = function () {
- xhr.abort();
- cleanUp();
- };
- var timeoutReq = function () {
- timedout = true;
- xhr.abort();
- cleanUp();
- };
- var ret = {abort: abortReq};
- var cleanUp = function () {
- clearTimeout(timer);
- ret.abort = function () {};
- xhr = undefined;
- };
- if (options.method === 'GET') {
- delete options.headers['Content-Type'];
- } else if (options.json) {
- options.headers.Accept = 'application/json';
- options.headers['Content-Type'] = options.headers['Content-Type'] ||
- 'application/json';
- if (options.body &&
- options.processData &&
- typeof options.body !== "string") {
- options.body = JSON.stringify(options.body);
- }
- }
- if (!('body' in options)) {
- options.body = null;
- }
- var dataType = options.binary ? 'arraybuffer' : 'json';
- var responseType = options.body && (options.body instanceof Blob) ? 'arraybuffer' : 'text';
- var headers = {};
- delete options.headers['Referer'];
- for (var key in options.headers) {
- if (options.headers.hasOwnProperty(key)) {
- headers[key] = options.headers[key];
- }
- }
- if (options.timeout > 0) {
- timer = setTimeout(timeoutReq, options.timeout);
- }
- var success = function(ret) {
- if (ret.statusCode >= 200 && ret.statusCode < 300) {
- var data = options.binary ? createBlob([ret.data || ''],{type: ret.header['Content-Type']}) : JSON.stringify(ret.data)
- callback(null,{statusCode: ret.statusCode},data)
- }
- else {
- var err = {};
- if (timedout) {
- err = new Error('ETIMEDOUT');
- err.code = 'ETIMEDOUT';
- } else if (typeof ret === 'object') {
- err = ret
- }
- err.status = ret.statusCode;
- callback(err);
- }
- }
- var fail = function(ret) {
- var err = UNKNOWN_ERROR;
- if (timedout) {
- err = new Error('ETIMEDOUT');
- err.code = 'ETIMEDOUT';
- } else if (typeof ret === 'object') {
- err = ret;
- } else if (typeof ret === 'string') {
- err = new PouchError(500, 'wechat_error', ret);
- }
- callback(err);
- }
- var complete = function() {
- cleanUp()
- }
- if (options.body && (options.body instanceof Blob)) {
- readAsArrayBuffer(options.body, function (arrayBuffer) {
- xhr = wx.request({
- url : options.url,
- data : arrayBuffer,
- header : headers,
- method : options.method,
- dataType : dataType,
- responseType : responseType,
- success : success,
- fail : fail,
- complete : complete
- })
- });
- } else {
- xhr = wx.request({
- url : options.url,
- data : options.body,
- header : headers,
- method : options.method,
- dataType : dataType,
- responseType : responseType,
- success : success,
- fail : fail,
- complete : complete
- })
- }
- return ret;
- }
Add Comment
Please, Sign In to add comment