Guest User

Untitled

a guest
Jul 19th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. /*
  2. Class: Ajax connectivity
  3. */
  4.  
  5. // Default constructor
  6. function Ajax(_options) {
  7. // Set that reference
  8. var that = this;
  9.  
  10. // Properties
  11. that.action = _options.action || undefined;
  12. that.method = _options.method || "GET";
  13. that.async = _options.async || true;
  14. that.params = _options.params || null;
  15. that.comet = _options.comet || false;
  16. that.success = _options.callback;
  17. that.error = _options.error;
  18.  
  19. // Functions
  20. that.sanitizeToLastJson = function(_string) {
  21. return string.substring(_string.lastIndexOf("{"), _string.lastIndexOf("}")+1);
  22. }
  23.  
  24. // Cancel if they omit this one
  25. if(typeof(that.action) === "undefined") {
  26. return false;
  27. }
  28.  
  29. // Connect immediately
  30. try {
  31. that.request = new XMLHttpRequest() || new ActiveXObject("MSXML2.XMLHTTP.3.0");
  32.  
  33. // Determine where get/post parameters go
  34. if(that.method === "GET" && that.params !== null) {
  35. that.request.open(that.method, that.action+"?"+encodeURI(that.params), that.async);
  36. }
  37. else {
  38. that.request.open(that.method, that.action, true);
  39. }
  40.  
  41. // Set content header for json
  42. that.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  43.  
  44. // Waiting for connect
  45. that.request.onreadystatechange = function() {
  46. // Using comet
  47. if(that.comet === true) {
  48. if(that.request.readyState === 3 && that.request.status === 200) {
  49. // If the success callback was set, call it
  50. if(typeof(that.success) !== "undefined") {
  51. that.success(that.sanitizeToLastJson(that.request.responseText));
  52. }
  53. }
  54. }
  55.  
  56. // Success
  57. if(that.request.readyState === 4 && that.request.status === 200) {
  58. // If the success callback was set, call it
  59. if(typeof(that.success) !== "undefined") {
  60. that.success(that.request.responseText);
  61. }
  62. }
  63. }
  64.  
  65. // Send the request differently if there is POST data
  66. if(that.method === "POST" && that.params !== null) {
  67. that.request.send(that.params);
  68. }
  69. else {
  70. that.request.send(null);
  71. }
  72.  
  73. return true;
  74. }
  75. catch (e) {
  76. // Call the error callback if set
  77. if(typeof(that.error) !== "undefined") {
  78. that.error(e);
  79. }
  80.  
  81. return false;
  82. }
  83. }
Add Comment
Please, Sign In to add comment