|
| 1 | +(function (global) { |
| 2 | + |
| 3 | +// Set up a namespace for our utility |
| 4 | +var ajaxUtils = {}; |
| 5 | + |
| 6 | + |
| 7 | +// Returns an HTTP request object |
| 8 | +function getRequestObject() { |
| 9 | + if (window.XMLHttpRequest) { |
| 10 | + return (new XMLHttpRequest()); |
| 11 | + } |
| 12 | + else if (window.ActiveXObject) { |
| 13 | + // For very old IE browsers (optional) |
| 14 | + return (new ActiveXObject("Microsoft.XMLHTTP")); |
| 15 | + } |
| 16 | + else { |
| 17 | + global.alert("Ajax is not supported!"); |
| 18 | + return(null); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | +// Makes an Ajax GET request to 'requestUrl' |
| 24 | +ajaxUtils.sendGetRequest = |
| 25 | + function(requestUrl, responseHandler, isJsonResponse) { |
| 26 | + var request = getRequestObject(); |
| 27 | + request.onreadystatechange = |
| 28 | + function() { |
| 29 | + handleResponse(request, |
| 30 | + responseHandler, |
| 31 | + isJsonResponse); |
| 32 | + }; |
| 33 | + request.open("GET", requestUrl, true); |
| 34 | + request.send(null); // for POST only |
| 35 | + }; |
| 36 | + |
| 37 | + |
| 38 | +// Only calls user provided 'responseHandler' |
| 39 | +// function if response is ready |
| 40 | +// and not an error |
| 41 | +function handleResponse(request, |
| 42 | + responseHandler, |
| 43 | + isJsonResponse) { |
| 44 | + if ((request.readyState == 4) && |
| 45 | + (request.status == 200)) { |
| 46 | + |
| 47 | + // Default to isJsonResponse = true |
| 48 | + if (isJsonResponse == undefined) { |
| 49 | + isJsonResponse = true; |
| 50 | + } |
| 51 | + |
| 52 | + if (isJsonResponse) { |
| 53 | + responseHandler(JSON.parse(request.responseText)); |
| 54 | + } |
| 55 | + else { |
| 56 | + responseHandler(request.responseText); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | + |
| 62 | +// Expose utility to the global object |
| 63 | +global.$ajaxUtils = ajaxUtils; |
| 64 | + |
| 65 | + |
| 66 | +})(window); |
| 67 | + |
0 commit comments