在这个社会转型期,最大的悲剧不是坏人的嚣张,而是好人的过度沉默。——马丁·路德·金
非常简单啦~
大家可以拿去任意定制,比如请求方式使用参数传入、指定参数类型、调用时控制是否同步等
var Ajax = {
dataFormat: function (data) { if (data == null || "" === data) { return ""; } return "?" + Object.keys(data).map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]); }).join("&"); },
get: function (url, data, fn) { var xhr = new XMLHttpRequest(); xhr.open('GET', url + this.dataFormat(data), false); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200 || xhr.status == 304) { var responseText = xhr.responseText var response = JSON.parse(responseText); } } } xhr.send(); },
post: function (url, data, fn) { var xhr = new XMLHttpRequest(); xhr.open('POST', url, false); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200 || xhr.status == 304) { var responseText = xhr.responseText var response = JSON.parse(responseText); } } } xhr.send(data); } }
|