简易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>

上一篇:jQuery实现商品楼层的感觉


下一篇:hdu_5927_Auxiliary Set(xjb搞)