ajax.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var ajax = {};
  2. ajax.xhr = {};
  3. ajax.xhr.Request = function(url, params, callback, method) {
  4. this.url = url;
  5. this.params = params;
  6. this.callback = callback;
  7. this.method = method;
  8. this.send();
  9. }
  10. ajax.xhr.Request.prototype = {
  11. getXMLHttpRequest: function() {
  12. if (window.ActiveXObject) {
  13. try {
  14. return new ActiveXObject("Msxml2.XMLHTTP");
  15. } catch(e) {
  16. try {
  17. return new ActiveXObject("Microsoft.XMLHTTP");
  18. } catch(e1) { return null; }
  19. }
  20. } else if (window.XMLHttpRequest) {
  21. return new XMLHttpRequest();
  22. } else {
  23. return null;
  24. }
  25. },
  26. send: function() {
  27. this.req = this.getXMLHttpRequest();
  28. var httpMethod = this.method ? this.method : 'GET';
  29. if (httpMethod != 'GET' && httpMethod != 'POST') {
  30. httpMethod = 'GET';
  31. }
  32. var httpParams = (this.params == null || this.params == '') ?
  33. null : this.params;
  34. var httpUrl = this.url;
  35. if (httpMethod == 'GET' && httpParams != null) {
  36. httpUrl = httpUrl + "?" + httpParams;
  37. }
  38. this.req.open(httpMethod, httpUrl, true);
  39. this.req.setRequestHeader(
  40. 'Content-Type', 'application/x-www-form-urlencoded');
  41. var request = this;
  42. this.req.onreadystatechange = function() {
  43. request.onStateChange.call(request);
  44. }
  45. this.req.send(httpMethod == 'POST' ? httpParams : null);
  46. },
  47. onStateChange: function() {
  48. this.callback(this.req);
  49. }
  50. }