一、定义Ajax请求数据的接口,ts封装ajax

  1. // 1.定义接口约束
  2. interface Config {
  3. type: string;
  4. url: string;
  5. data?: string; // 可传可不传
  6. dataType: string;
  7. }
  8. // 2.原生js封装的ajax
  9. function ajax(config: Config) {
  10. var xhr = new XMLHttpRequest();
  11. xhr.open(config.type, config.url, true);
  12. xhr.send(config.data);
  13. xhr.onreadystatechange = function () {
  14. if (xhr.readyState == 4 && xhr.status == 200) {
  15. if (config.dataType == 'json') {
  16. console.log(JSON.parse(xhr.responseText));
  17. } else {
  18. console.log(xhr.responseText)
  19. }
  20. }
  21. }
  22. }
  23. ajax({
  24. type: 'get',
  25. data: 'name=zhangsan',
  26. url: 'http://a.itying.com/api/productlist',
  27. dataType: 'json'
  28. })