-
-
Save yangsu/61b650af7b804bd9170b 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
/*globals ActiveXObject*/ | |
// Cross browser Ajax implementation based on | |
// http://toddmotto.com/writing-a-standalone-ajax-xhr-javascript-micro-library/ | |
// https://gist.github.com/Xeoncross/7663273 | |
var encodeParams = function(data, bustCache) { | |
var key, | |
params = []; | |
for (key in data) { | |
if (data.hasOwnProperty(key)) { | |
params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); | |
} | |
} | |
if (bustCache) { | |
params.push('_t=' + Date.now()); | |
} | |
return params.join('&'); | |
}; | |
var parse = function(req) { | |
var result; | |
try { | |
result = JSON.parse(req.responseText); | |
} catch (e) { | |
result = req.responseText; | |
} | |
return [result, req]; | |
}; | |
var xhr = function(type, url, data) { | |
var methods = { | |
success: function() {}, | |
error: function() {} | |
}; | |
var XHR = window.XMLHttpRequest || ActiveXObject; | |
var request = new XHR('MSXML2.XMLHTTP.3.0'); | |
request.open(type, url, true); | |
if (type === 'POST') { | |
xhr.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
} | |
if (data) { | |
data = encodeParams(data); | |
} | |
request.onreadystatechange = function() { | |
if (request.readyState === 4) { | |
if (request.status === 200) { | |
methods.success.apply(methods, parse(request)); | |
} else { | |
methods.error.apply(methods, parse(request)); | |
} | |
} | |
}; | |
request.send(data); | |
return { | |
success: function(callback) { | |
methods.success = callback; | |
return methods; | |
}, | |
error: function(callback) { | |
methods.error = callback; | |
return methods; | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment