Last active
August 29, 2015 13:59
-
-
Save amatiasq/10876791 to your computer and use it in GitHub Desktop.
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
(function(global) { | |
'use strict'; | |
function chain(obj, method) { | |
var original = obj[method]; | |
obj[method] = function() { | |
original.apply(this, arguments); | |
return this; | |
}; | |
} | |
function HttpRequest() { | |
var xhr = new XMLHttpRequest(); | |
chain(xhr, 'open'); | |
chain(xhr, 'setRequestHeader'); | |
var send = xhr.send; | |
xhr.send = function(data) { | |
var self = this; | |
return new Promise(function(resolve, reject) { | |
self.addEventListener('readystatechange', function(event) { | |
if (self.readyState === XMLHttpRequest.DONE) | |
resolve(self); | |
}); | |
send.apply(self, arguments); | |
}); | |
}; | |
return xhr; | |
} | |
global.HttpRequest = HttpRequest; | |
})(this); |
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
(function(global) { | |
'use strict'; | |
var count = 0; | |
function jsonp(url, options) { | |
return new Promise(function(resolve, reject) { | |
var separator = url.indexOf('?') !== -1 ? '&' : '?'; | |
var callback = '__mq_callback__' + count; | |
count++; | |
url += separator + 'callback=' + callback; | |
var tag = document.createElement('script'); | |
tag.setAttribute('type', 'text/javascript'); | |
tag.setAttribute('src', url); | |
document.head.appendChild(tag); | |
window[callback] = function(response) { | |
delete window[callback]; | |
document.head.removeChild(tag); | |
resolve(response); | |
}; | |
if (options && options.timeout) { | |
setTimeout(function() { | |
reject(new Error('Request timeout')); | |
}, options.timeout); | |
} | |
}); | |
} | |
global.HttpRequest.jsonp = jsonp; | |
})(this); |
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
function ajax() { | |
return new HttpRequest() | |
.open('POST', '/something.php') | |
.setRequestHeader('Content-Type', 'text/plain') | |
.send('Hello') | |
.then(function(request) { | |
return request.responseText; | |
}); | |
} | |
function jsonRequest(data) { | |
return new HttpRequest() | |
.open('POST', '/something.php') | |
.setRequestHeader('Content-Type', 'text/json') | |
.send(JSON.stringify(data)) | |
.then(function(request) { | |
return JSON.parse(request.responseText); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment