Last active
August 29, 2015 14:11
-
-
Save bertzzie/cca44a45bfed354e63b4 to your computer and use it in GitHub Desktop.
Implementasi AJAX mirip $.ajax jQuery.
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 MyLib = MyLib || {}; | |
MyLib.AJAX = function (options) { | |
if ("method" in options && | |
"url" in options && | |
"onSuccess" in options) { | |
var xhr, | |
method = options.method, | |
data = options.data, | |
url = options.url, | |
async = options.async || true, | |
onSuccess = options.onSuccess, | |
onFailure = options.onFailure || function () { }; | |
try { | |
xhr = new XMLHttpRequest(); | |
} catch (e) { | |
xhr = new ActiveXObject("Microsoft.XMLHTTP"); | |
} | |
if (xhr === undefined) { | |
alert("TIDAK MENDUKUNG AJAX"); | |
} | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState === 4) { | |
if (xhr.status === 200) { | |
onSuccess(xhr.responseText); | |
} else { | |
onFailure(); | |
} | |
} | |
}; | |
xhr.open(method, | |
url, | |
async); | |
xhr.send(data); | |
} else { | |
alert("Options tidak lengkap"); | |
} | |
}; | |
// Contoh penggunaan | |
var HandleData = function (data) { | |
// do something | |
}; | |
var HandleError = function () { | |
// do something | |
}; | |
var LogBaru = function (data) { | |
// do something | |
}; | |
MyLib.AJAX({ | |
method : "GET", | |
url : "http://contoh.com/ajaxapi/departments", | |
async : true, | |
onSuccess : HandleData, | |
onFailure : HandleError | |
}); | |
MyLib.AJAX({ | |
method : "POST", | |
url : "http://contoh.com/ajaxapi/departments/" + dept_no, | |
async : true, | |
onSuccess : LogBaru, | |
onFailure : HandleError | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment