ajax.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. function _loadScript(url, fn) {
  2. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  3. script = document.createElement('script');
  4. head.appendChild(script);
  5. script.src = url;
  6. script.charset = 'utf-8';
  7. script.onload = script.onreadystatechange = function() {
  8. if (!this.readyState || this.readyState === 'loaded') {
  9. if (fn) {
  10. fn();
  11. }
  12. script.onload = script.onreadystatechange = null;
  13. head.removeChild(script);
  14. }
  15. };
  16. }
  17. // 移除URL里的GET参数
  18. function _chopQuery(url) {
  19. var index = url.indexOf('?');
  20. return index > 0 ? url.substr(0, index) : url;
  21. }
  22. function _loadStyle(url) {
  23. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  24. link = document.createElement('link'),
  25. absoluteUrl = _chopQuery(_formatUrl(url, 'absolute'));
  26. var links = K('link[rel="stylesheet"]', head);
  27. for (var i = 0, len = links.length; i < len; i++) {
  28. if (_chopQuery(_formatUrl(links[i].href, 'absolute')) === absoluteUrl) {
  29. return;
  30. }
  31. }
  32. head.appendChild(link);
  33. link.href = url;
  34. link.rel = 'stylesheet';
  35. }
  36. function _ajax(url, fn, method, param, dataType) {
  37. method = method || 'GET'; //POST or GET
  38. dataType = dataType || 'json'; //json or html
  39. var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  40. xhr.open(method, url, true);
  41. xhr.onreadystatechange = function () {
  42. if (xhr.readyState == 4 && xhr.status == 200) {
  43. if (fn) {
  44. var data = _trim(xhr.responseText);
  45. if (dataType == 'json') {
  46. data = _json(data);
  47. }
  48. fn(data);
  49. }
  50. }
  51. };
  52. if (method == 'POST') {
  53. var params = [];
  54. _each(param, function(key, val) {
  55. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
  56. });
  57. try {
  58. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  59. } catch (e) {}
  60. xhr.send(params.join('&'));
  61. } else {
  62. xhr.send(null);
  63. }
  64. }
  65. K.loadScript = _loadScript;
  66. K.loadStyle = _loadStyle;
  67. K.ajax = _ajax;