ajax.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var isFn = require('./isFn');
  2. var noop = require('./noop');
  3. var defaults = require('./defaults');
  4. var isObj = require('./isObj');
  5. var query = require('./query');
  6. exports = function(options) {
  7. defaults(options, exports.setting);
  8. var type = options.type;
  9. var url = options.url;
  10. var data = options.data;
  11. var dataType = options.dataType;
  12. var success = options.success;
  13. var error = options.error;
  14. var timeout = options.timeout;
  15. var complete = options.complete;
  16. var xhr = options.xhr();
  17. var abortTimeout;
  18. xhr.onreadystatechange = function() {
  19. if (xhr.readyState !== 4) return;
  20. clearTimeout(abortTimeout);
  21. var result;
  22. var status = xhr.status;
  23. if ((status >= 200 && status < 300) || status === 304) {
  24. result = xhr.responseText;
  25. if (dataType === 'xml') result = xhr.responseXML;
  26. try {
  27. if (dataType === 'json') result = JSON.parse(result);
  28. } catch (e) {}
  29. success(result, xhr);
  30. } else {
  31. error(xhr);
  32. }
  33. complete(xhr);
  34. };
  35. if (type === 'GET') {
  36. data = query.stringify(data);
  37. if (data) url += url.indexOf('?') > -1 ? '&' + data : '?' + data;
  38. } else if (options.contentType === 'application/x-www-form-urlencoded') {
  39. if (isObj(data)) data = query.stringify(data);
  40. } else if (options.contentType === 'application/json') {
  41. if (isObj(data)) data = JSON.stringify(data);
  42. }
  43. xhr.open(type, url, true);
  44. xhr.setRequestHeader('Content-Type', options.contentType);
  45. if (timeout > 0) {
  46. abortTimeout = setTimeout(function() {
  47. xhr.onreadystatechange = noop;
  48. xhr.abort();
  49. error(xhr, 'timeout');
  50. complete(xhr);
  51. }, timeout);
  52. }
  53. xhr.send(type === 'GET' ? null : data);
  54. return xhr;
  55. };
  56. exports.setting = {
  57. type: 'GET',
  58. success: noop,
  59. error: noop,
  60. complete: noop,
  61. dataType: 'json',
  62. contentType: 'application/x-www-form-urlencoded',
  63. data: {},
  64. xhr: function() {
  65. return new XMLHttpRequest();
  66. },
  67. timeout: 0
  68. };
  69. exports.get = function() {
  70. return exports(parseArgs.apply(null, arguments));
  71. };
  72. exports.post = function() {
  73. var options = parseArgs.apply(null, arguments);
  74. options.type = 'POST';
  75. return exports(options);
  76. };
  77. function parseArgs(url, data, success, dataType) {
  78. if (isFn(data)) {
  79. dataType = success;
  80. success = data;
  81. data = {};
  82. }
  83. return {
  84. url: url,
  85. data: data,
  86. success: success,
  87. dataType: dataType
  88. };
  89. }
  90. module.exports = exports;