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