AjaxUtil.js 981 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. function ajaxGet(option) {
  2. if (!option.url) {
  3. return alert('url 必传');
  4. }
  5. let xhr = new XMLHttpRequest();
  6. let str = '';
  7. if (option.query) {
  8. str = '?';
  9. for (let key in option.query) {
  10. str += `${encodeURIComponent(key)}=${encodeURIComponent(option.query[key])}&`;
  11. }
  12. str = str.slice(0, -1); // 去掉最后的 &
  13. }
  14. xhr.open('GET', option.url + str);
  15. xhr.send();
  16. xhr.onreadystatechange = () => {
  17. if (xhr.readyState === 4) {
  18. if (xhr.status === 200) {
  19. option.success && option.success(xhr.responseText);
  20. } else {
  21. option.error && option.error(xhr.responseText);
  22. }
  23. }
  24. };
  25. }
  26. // 使用示例
  27. ajaxGet({
  28. url: '2024demo.txt',
  29. query: {
  30. name: 'zhangsanfeng',
  31. age: 20
  32. },
  33. success: (data) => {
  34. console.log(data);
  35. },
  36. error: (err) => {
  37. console.error(err);
  38. }
  39. });