XMLHttpRequest请求

XMLHttpRequest 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* [json 实现ajax的json]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
util.json = function(options) {
var opt = {
url: "",
type: "get",
data: {},
success: function() {},
error: function() {}
}
util.extend(opt, options)
if (opt.url) {
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
var data = opt.data,
url = opt.url,
type = opt.type.toUpperCase(),
dataArr = []
for (var k in data) {
// 将ke-value的数据转成数组存放
dataArr.push(k + "=" + data[k])
}
if (type === "GET") {
url = url + "?" + dataArr.join("&")
// 删除以问号结尾的问号
xhr.open(type, url.replace(/\?$/g, ""), true)
xhr.send()
}
if (type === "POST") {
xhr.open(type, url, true)
// 设置请求头部
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.send(dataArr.join("&"))
}
xhr.onload = function() {
// 304 客户端可从缓存中获取数据,还可以增加 206 视频等媒体资源加载时用
if (xhr.status === 200 || xhr.status === 304) {
var res
if (opt.success && opt.success instanceof Function) {
res = xhr.responseText
if (typeof res === "string") {
res = JSON.parse(res)
opt.success.call(xhr, res)
}
}
} else {
if (opt.error && opt.error instanceof Function) {
opt.error.call(xhr, res)
}
}
}
}
}