common.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const getRootPath = () => {
  2. const protocol = window.location.protocol;
  3. const host = window.location.host;
  4. const localhostPath = protocol + '//' + host;
  5. // return 'http://192.168.1.6:10026';
  6. return localhostPath;
  7. }
  8. // 获取API的地址
  9. const getApiURL = (apiName) => {
  10. return getRootPath() + apiName;
  11. // return 'http://192.168.1.112:10026' + apiName;
  12. }
  13. const ajaxGet = (url, data) => {
  14. let requestUrl = url
  15. let paramCount = 0;
  16. if (data) {
  17. data.forEach(item => {
  18. requestUrl += (paramCount > 0) ? '&' : '?';
  19. requestUrl += (`${item[0]}` + `=${item[1]}`);
  20. paramCount++;
  21. })
  22. }
  23. return new Promise((resolve, reject) => {
  24. $.ajax({
  25. url: getApiURL(requestUrl),
  26. type: 'get',
  27. contentType: 'application/json',
  28. beforeSend: function (request) {
  29. request.setRequestHeader('token', localStorage.getItem('#token'));
  30. },
  31. success: function (data) {
  32. resolve(data);
  33. },
  34. error: function (XMLHttpRequest, textStatus, errorThrown) {
  35. reject(XMLHttpRequest);
  36. },
  37. });
  38. });
  39. }
  40. const ajaxPost = (url, params) => {
  41. return new Promise((resolve, reject) => {
  42. $.ajax({
  43. url: getApiURL(url),
  44. type: 'post',
  45. contentType: 'application/json',
  46. data: JSON.stringify(params),
  47. success: function (data) {
  48. resolve(data);
  49. },
  50. error: function (XMLHttpRequest, textStatus, errorThrown) {
  51. reject(XMLHttpRequest);
  52. },
  53. });
  54. });
  55. }