Created
August 6, 2017 09:12
-
-
Save davidgarsan/38e17667ad79ac3d36644e42a3ba2e49 to your computer and use it in GitHub Desktop.
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
var xhr = function() { | |
var xhr = new XMLHttpRequest(); | |
var mapper = function(data) { | |
return Object.keys(data).map(function(k) { | |
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) | |
}).join('&'); | |
}; | |
return function(method, url, data, success, error, isJSON, headers) { | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) { | |
if (xhr.status === 200 && success) { | |
success(isJSON? JSON.parse(xhr.responseText) : xhr.responseText); | |
} else if (error) { | |
error(); | |
} | |
} | |
}; | |
url += (data && method === 'GET') ? mapper(data) : ''; | |
xhr.open(method, url); | |
if (headers) { | |
for(header in headers) { | |
xhr.setRequestHeader(header, headers[header]); | |
}; | |
} | |
// xhr.setRequestHeader("Content-Type", "application/json"); | |
xhr.send((data && method === 'POST') ? JSON.stringify(data) : ''); | |
}; | |
}(); | |
// xhr('GET', 'url', JSONheaders, function(data){console.log(JSON.parse(data))}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment