Last active
February 3, 2016 01:53
-
-
Save interjc/53f574fc6d7c67b98046 to your computer and use it in GitHub Desktop.
Promise XHR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// 函数封装 | |
var handleAjax = function handleAjax() { | |
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0], | |
opt = { | |
url: options.url || '', | |
data: options.data || 't=' + new Date().getTime(), | |
type: options.type || 'get', | |
dataType: options.dataType || 'json', | |
cache: options.cache || false, | |
async: options.async || true, | |
context: options.context || document.body, | |
beforeSend: options.beforeSend || undefined | |
}; | |
return new Promise(function (resolve, reject) { | |
var req = new XMLHttpRequest(); | |
if (typeof opt.beforeSend === 'function') { | |
opt.beforeSend(); | |
} | |
req.open(opt.type, opt.url, opt.async); | |
req.onload = function () { | |
if (req.status === 200) { | |
var data = req.responseText; | |
if (opt.dataType === 'json') { | |
data = JSON.parse(data); | |
} | |
resolve(data); | |
} else { | |
reject(new Error(req.statusText || 'You can\'t do this.')); | |
} | |
}; | |
req.onerror = function () { | |
reject(new Error(req.statusText || 'Server is down.')); | |
}; | |
req.send(); | |
}); | |
}; | |
// 调用函数 | |
var options = { | |
url: 'http://httpbin.org/get' | |
}; | |
handleAjax(options).then(function (data) { | |
console.log(data); | |
})['catch'](function (error) { | |
console.log(error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment