1 /** 2 * Ajax 3 * 4 * Module for making ajax requests 5 */ 6 (function (){ 7 8 var ajax = { 9 _do: function (url, data, callback, isPost) 10 { 11 if (typeof callback === "undefined") 12 { 13 /** 14 * @private 15 */ 16 callback = function (){}; 17 } 18 19 var request = (typeof window.XMLHttpRequest !== "undefined") 20 ? new XMLHttpRequest() 21 : false; 22 23 var type = (isPost) ? "POST" : "GET"; 24 25 url += (type === "GET") ? "?"+this._serialize(data) : ''; 26 27 request.open(type, url); 28 29 request.onreadystatechange = function () 30 { 31 if (request.readyState === 4) 32 { 33 callback(request.responseText); 34 } 35 }; 36 37 if (type === "POST") 38 { 39 request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 40 request.send(this._serialize(data)); 41 } 42 else 43 { 44 request.send(null); 45 } 46 }, 47 _serialize: function (data) 48 { 49 var pairs = []; 50 51 for (var name in data) 52 { 53 if (!data.hasOwnProperty(name)) 54 { 55 continue; 56 } 57 if (typeof data[name] === "function") 58 { 59 continue; 60 } 61 62 var value = data[name].toString(); 63 64 name = encodeURIComponent(name); 65 value = encodeURIComponent(value); 66 67 pairs.push(name + "=" + value); 68 } 69 70 return pairs.join("&"); 71 } 72 }; 73 74 /** 75 * Sends a GET type ajax request 76 * 77 * @name get 78 * @function 79 * @memberOf $_ 80 * @param string url 81 * @param object data 82 * @param function callback 83 * @return void 84 */ 85 $_.ext('get', function (url, data, callback){ 86 ajax._do(url, data, callback, false); 87 }); 88 89 /** 90 * Sends a POST type ajax request 91 * 92 * @name post 93 * @function 94 * @memberOf $_ 95 * @param string url 96 * @param object data 97 * @param function callback 98 * @return void 99 */ 100 $_.ext('post', function (url, data, callback){ 101 ajax._do(url, data, callback, true); 102 }); 103 }());