ajax.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. function ajax(options) {
  2. options = options || {};
  3. options.type = (options.type || "GET").toUpperCase();
  4. options.dataType = options.dataType || "json";
  5. var params = formatParams(options.data);
  6. //创建 - 非IE6 - 第一步
  7. if (window.XMLHttpRequest) {
  8. var xhr = new XMLHttpRequest();
  9. } else { //IE6及其以下版本浏览器
  10. var xhr = new ActiveXObject('Microsoft.XMLHTTP');
  11. }
  12. //接收 - 第三步
  13. xhr.onreadystatechange = function () {
  14. if (xhr.readyState == 4) {
  15. var status = xhr.status;
  16. if (status >= 200 && status < 300) {
  17. options.success && options.success(xhr.responseText, xhr.responseXML);
  18. } else {
  19. options.fail && options.fail(status);
  20. }
  21. }
  22. }
  23. //连接 和 发送 - 第二步
  24. if (options.type == "GET") {
  25. xhr.open("GET", options.url + "?" + params, true);
  26. xhr.send(null);
  27. } else if (options.type == "POST") {
  28. xhr.open("POST", options.url, true);
  29. //设置表单提交时的内容类型
  30. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  31. xhr.send(params);
  32. }
  33. return xhr;
  34. }
  35. //格式化参数
  36. function formatParams(data) {
  37. var arr = [];
  38. for (var name in data) {
  39. arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
  40. }
  41. arr.push(("v=" + Math.random()).replace(".",""));
  42. return arr.join("&");
  43. }