Last active
December 17, 2015 00:59
-
-
Save joseanpg/5525517 to your computer and use it in GitHub Desktop.
SimpleHttpRequest
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
http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-setrequestheader |
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(module){ | |
var hop = Object.prototype.hasOwnProperty; | |
var urlEncode = function(flatObject) { | |
var result = []; | |
for (var p in flatObject) if (hop.call(flatObject,p)) { | |
result.push(encodeURIComponent(p)+'='+encodeURIComponent(flatObject[p])); | |
} | |
return result.join('&'); | |
} | |
var httpRequesterFactory = (function() { | |
if (typeof XMLHttpRequest === 'function') { | |
return function(){return new XMLHttpRequest()}; | |
} | |
else { | |
try { | |
return function(){return new ActiveXObject("Msxml2.XMLHTTP");} | |
} | |
catch(ex){ | |
try { | |
return function(){return new ActiveXObject("Microsoft.XMLHTTP");} | |
} | |
catch(ex){ | |
throw ex; | |
} | |
} | |
} | |
})(); | |
var httpKernel = function(method,url, data, headerName, headerValue) { | |
var good, bad; | |
var r = httpRequesterFactory(); | |
r.onreadystatechange = function(){ | |
if (r.readyState === 4) { | |
if (r.status === 200) | |
good(r.responseText); | |
else | |
bad(r.responseText); | |
} | |
} | |
r.open(method,url); | |
if (typeof headerName !== 'undefined') r.setRequestHeader(headerName,headerValue); | |
r.send(data); | |
return function(g,b){good = g; bad = b;}; | |
} | |
var httpGet = function(url, data) { | |
if (typeof data !== 'undefined') | |
url = url +'?'+urlEncode(data); | |
return httpKernel('GET',url,null) | |
} | |
var httpPost = function(url, data) { | |
data = urlEncode(data); | |
return httpKernel('POST',url,data,'Content-type','application/x-www-form-urlencoded'); | |
} | |
module.httpPost = httpPost; | |
module.httpGet = httpGet; | |
})(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment