1function ajax(setting) {
2 const ajax = new XMLHttpRequest()
3 // 默认 get
4 if (!setting.method)
5 setting.method = 'get'
6
7 // 组合data查询数据
8 if (setting.data)
9 setting.data = getSearch(setting.data)
10 else
11 setting.data = ''
12
13 if (setting.method.toLowerCase() == 'get') {
14 ajax.open('get', `${setting.url}?${setting.data}`, true)
15 ajax.send()
16 }
17 else if (setting.method.toLowerCase() == 'post') {
18 ajax.open('post', setting.url, true)
19 ajax.setRequestHeader('Content-type', 'appliction/x-www-form-urlencoded')
20 ajax.send(setting.data)
21 }
22
23 ajax.onreadystatechange = function () {
24 if (ajax.readyState == 4) {
25 if (ajax.status == 200)
26 setting.success(ajax.responseText)
27 else
28 console.log(`Error:${ajax.status}`)
29 }
30 }
31}
32
33// 拼接字符串
34function getSearch(obj) {
35 let str = ''
36 for (const key in obj)
37 str += `${key}=${obj[key]}&`
38
39 return str.slice(0, str.length - 1)
40}