Created
June 8, 2017 09:40
-
-
Save ishowshao/9b21a6e9eaa589d2ba3e03c2e1f8253a to your computer and use it in GitHub Desktop.
ajax on fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file | |
* @author shaoshuai | |
*/ | |
export default { | |
queryString(data) { | |
let body = []; | |
for (let [key, value] of Object.entries(data)) { | |
body.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); | |
} | |
return body.join('&'); | |
}, | |
/** | |
* 发送POST请求 | |
* | |
* @param {string} url | |
* @param {Object} data | |
* @return {Promise} | |
*/ | |
post(url, data = {}) { | |
return fetch(url, { | |
method: 'POST', | |
body: this.queryString(data), | |
credentials: 'include', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
} | |
}).then(response => response.json()); | |
}, | |
/** | |
* 发送DELETE请求 | |
* | |
* @param {string} url | |
* @param {Object} data | |
* @return {Promise} | |
*/ | |
delete(url, data = {}) { | |
return fetch(url, { | |
method: 'DELETE', | |
body: this.queryString(data), | |
credentials: 'include', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
} | |
}).then(response => response.json()); | |
}, | |
/** | |
* 发送GET请求 | |
* | |
* @param {string} url | |
* @param {Object} data | |
* @return {Promise} | |
*/ | |
get(url, data = {}) { | |
let qs = this.queryString(data); | |
if (qs !== '') { | |
let sep = url.indexOf('?') === -1 ? '?' : '&'; | |
url = url + sep + qs; | |
} | |
return fetch(url, {credentials: 'include'}).then(response => response.json()); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment