自定义封装ajax,复制即可用

支持get、post请求

 <!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title>自定义封装ajax</title>
</head> <body>
</body> </html>
<script type="text/javascript">
function ajax(obj) { obj = obj || {};
obj.method = obj.method.toUpperCase() || "POST";
obj.url = obj.url || "";
obj.async = obj.async || true;
obj.data = obj.data || null;
obj.success = obj.success || function() {};
obj.headers = obj.headers || null;
var xmlHttp = null; if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); //非IE浏览器 } else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") //IE
} // 处理参数 if(obj.method.toUpperCase() == "POST") {
xmlHttp.open(obj.method, obj.url, obj.async); if(obj.headers.ContentType) { xmlHttp.setRequestHeader("Content-Type", obj.headers.ContentType); } else { xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); } xmlHttp.send(JSON.stringify(obj.data)); //到了这的post是各个参数拼接在一起了,类似get请求??????????
} else {
var par = []; for(var key in obj.data) { par.push(key + '=' + obj.data[key]) }
var postData = par.join("&"); xmlHttp.open(obj.method, obj.url + "?" + postData, obj.async);
xmlHttp.send(null) } xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
obj.success(JSON.parse(xmlHttp.responseText))
} } } //get请求实例
ajax({ method: 'get',
url: "http://risk.haitun.hk/risk-console/risk/messageInfo/list",
data: {
msgType: 1,
pageNum: 1,
pageSize: 6
},
success: function(res) {
console.log(res, 'get请求实例')
} }) //post请求实例
ajax({
method: 'POST',
url: "http://risk.haitun.hk/risk-console/risk/riskRule/list",
data: {
pageNum: 1,
pageSize: 10
},
async: false,
headers: {
"ContentType": "application/json;charset=utf-8" //注意头部,ContentType
},
success: function(res) { console.log(res, 'post请求实例') }
})
</script>
上一篇:tensorflow中的Supervisor


下一篇:Web 在线文件管理器学习笔记与总结(13)重命名文件夹(14)复制文件夹