热搜:m1 nginx 代理 前端

前端开发中通用的ajax 封装

admin2024-04-03 09:30:01

前端开发中通用的ajax 封装 1

function ajax (url, method, postData) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText));
        } else {
          reject(new Error(xhr.responseText));
        }
      }
    }
    method === 'GET' ? xhr.send() : xhr.send(JSON.stringify(postData));
  });
}