XMLHttpRequest请求 发表于 2018-04-13 | 分类于 JavaScript XMLHttpRequest 请求12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455/** * [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) } } } }}