赞
踩
- class Ajax {
- constructor(xhr) {
- xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
- this.xhr = xhr;
- }
- send(options) {
- let xhr = this.xhr;
- let ajax = {
- type: options.type || 'GET',
- url: options.url || '',
- async: options.async || 'true',
- dataType: options.dataType || 'json',
- data: options.data || ''
- };
- return new Promise((resolve, reject) => {
- let dataList = [];
- for (let key in ajax.data) {
- dataList.push(key + '=' + ajax.data[key])
- }
- let dataStr = dataList.join("&");
-
- if (ajax.type === "get" || ajax.type === "GET") {
- console.log(dataStr);
-
- ajax.url = dataStr ? ajax.url + "?" + dataStr : ajax.url;
- console.log(ajax.url);
- xhr.open(ajax.type, ajax.url, ajax.async);
- xhr.send();
- }
- if (ajax.type === "post" || ajax.type === "POST") {
- xhr.open(ajax.type, ajax.url, ajax.async);
- xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- if (ajax.data) {
- xhr.send(ajax.data);
- } else {
- xhr.send();
- }
- }
-
- xhr.onreadystatechange = () => {
- if (xhr.readyState === 4) {
- if (xhr.status >= 200 && xhr.status < 400) {
- const data = JSON.parse(xhr.response);
- resolve(data);
- console.log(data);
- } else if (xhr.status >= 400) {
- const data = JSON.parse(xhr.response);
- console.log(data);
-
- reject(new Error(xhr.status || 'Server if sail'));
- }
- }
- }
-
- })
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。