Monday, September 22, 2014

Javascript: Simple Ajax Class

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 function $()
{
this.ajax = function (a) {
var c = new webClient();

c.onreadystatechange = function () {
if (c.readyState == 4) {
switch (c.status) {
case 200: if (typeof (a.success) == 'function') { a.success(c.responseText, c.status) } break;
default: if (typeof (a.error) == 'function') { a.error(c.responseText, c.status) }; break;
}
}
}

if (a.type == 'POST') {
c.open('POST', a.url, true);
c.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
c.send(a.data);
}

if (a.type == 'GET') {
c.open('GET', a.url, true);
c.send(null);
}
}

var webClient = function WebClient() {
var objs = [
function () { return new XMLHttpRequest() }, // Firefox, Opera 8.0+, Safari
function () { return new ActiveXObject("Msxml2.XMLHTTP") }, // Internet Explorer
function () { return new ActiveXObject("Msxml3.XMLHTTP") }, // Internet Explorer
function () { return new ActiveXObject("Microsoft.XMLHTTP") }]; // Internet Explorer

var h;
for (var i = 0; i < objs.length; i++) {
try {
h = objs[i]();
}
catch (e) {
continue;
}
break;
}
return h;
}
}

var $ = new $();


Use it like:

1 2 3 4 5 6 7 8 9 function Post() {
$.ajax({
url: window.location.href,
type: 'POST',
data: 'first=john&last=doe',
success: function (data, status) { alert(data) },
error: function (data, status) { alert(data) }
})
}

No comments:

Post a Comment