Last active
November 27, 2018 14:35
-
-
Save lilywang711/79368d6b119e66260f84858d215c0642 to your computer and use it in GitHub Desktop.
ajax.js
This file contains 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
const ajax = (options = {}) => { | |
options.method = (options.method || "GET").toUpperCase() | |
options.dataType = options.dataType || 'json' | |
options.async = options.async || true | |
let xhr = null | |
if (window.XMLHttpRequest) { | |
xhr = new XMLHttpRequest() | |
} else { | |
xhr = new ActiveXObject('Microsoft.XMLHTTP') | |
} | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState === 4) { | |
const status = xhr.status | |
if (status >= 200 && status < 300) { | |
options.success && options.success(JSON.parse(xhr.responseText)) | |
} else { | |
options.fail && options.fail(JSON.parse(xhr.responseText)) | |
} | |
} | |
} | |
if (options.method === 'GET') { | |
const params = getParams(options.data) | |
xhr.open("GET", options.url + '?' + params, options.async) | |
xhr.withCredentials = options.withCredentials || false | |
xhr.send(null) | |
} else { | |
xhr.open(options.method, options.url, options.async) | |
xhr.setRequestHeader('Content-Type', 'application/json') | |
const headers = options.header | |
for (let key in headers) { | |
xhr.setRequestHeader(key, headers[key]) | |
} | |
xhr.withCredentials = options.withCredentials || false | |
xhr.send(JSON.stringify(options.data)) | |
} | |
} | |
const getParams = (data) => { | |
if (typeof data !== 'object') return | |
let arr = [] | |
let params = '' | |
Object.keys(data).forEach(key => { | |
arr.push(`${key}=${encodeURIComponent(data[key])}`) | |
}) | |
return arr.join('&') | |
} | |
// 调用方法 | |
ajax({ | |
method: 'GET | POST | DELETE | PUT', | |
url: '', | |
data: { | |
// GET 时候的参数也放此 | |
}, | |
header: { | |
// 自定义 header | |
}, | |
withCredentials: false, | |
dataType:"json", | |
success: (res) => { | |
console.log(res) | |
}, | |
fail: (err) => { | |
console.log(err) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment