简易promise
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
/**
* Created by addison on 2014/4/4.
*/
//简易promise
(function (w) {
var a = {};
a.get = function (url) {
return new a.promise(a.ajax, url);
}
//简易ajax
a.ajax = function (url) {
var me = this;
var request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function () {
if (request.status == 200) {
me.success(request.responseText);
} else {
me.success(request);
}
};
request.onerror = function () {
reject(Error('Error fetching data.')); // error occurred, reject the Promise
};
request.send(); //send the request
}
a.promise = function (promise, url) {
promise.call(this, url);
}
a.promise.prototype.then = function (success, error) {
this.success = success;
this.error = error;
}
window.a = a;
}(window))
</script>
<script>
a.get('json or text').then(
function success(data) {
document.write(data);
}, function error() {
debugger;
})
</script>
</head>
<body>
</body>
</html>