1.新建js文件,例:ajax.js
var HttpRequest = function(options) {
var defaults = {
type: 'get',
headers: {},
data: {},
dataType: 'json',
async: true,
cache: false,
beforeSend: null,
success: null,
complete: null,
error: null
};
var o = $.extend({}, defaults, options);
$.ajax({
url: o.url,
type: o.type,
headers: {
'Content-Type': o.contentType,
'access_token': o.token
},
data: o.data,
dataType: o.dataType,
async: o.async,
beforeSend: function() {
o.beforeSend && o.beforeSend();
},
success: function(res) {
o.success && o.success(res);
},
complete: function() {
o.complete && o.complete();
},
error: function(err) {
o.error && o.error(err);
}
});
};
var loginHttp = function(options) {
// 登入页无需携带token
// 后台如果要求 Content-Type
if (options.type == 'post') {
options.contentType = 'application/x-www-form-urlencoded';
}
HttpRequest(options);
};
var ajaxHttp = function(options) {
if (options.type == 'post') {
options.contentType = 'application/x-www-form-urlencoded';
}
// 每次请求携带token
options.token = localStorage.getItem('access_token');
HttpRequest(options);
};
2.使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 简单封装ajax,每次请求自动携带token</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="./ajax.js"></script>
</head>
<body>
<button class="login">登入</button>
<button class="request">登入之后请求</button>
<script>
$('.login').click(function() {
loginHttp({
url: 'https://api.7585.net.cn/shici/api.php',
type: 'post',
data: {},
beforeSend: function() {
// loading 显示
},
success: function(res) {
console.log(res);
// 本地存入token
localStorage.setItem('access_token', 'access_token');
},
complete: function() {
// loading 关闭
},
error: function(err) {
console.log(err);
}
});
});
$('.request').click(function() {
ajaxHttp({
url: 'https://api.7585.net.cn/shici/api.php',
type: 'post',
data: {},
beforeSend: function() {
// loading 显示
},
success: function(res) {
console.log(res);
},
complete: function() {
// loading 关闭
}
});
});
</script>
</body>
</html>
如果本篇文章对你有帮助的话,很高兴能够帮助上你。
当然,如果你觉得文章有什么让你觉得不合理、或者有更简单的实现方法又或者有理解不来的地方,希望你在看到之后能够在评论里指出来,我会在看到之后尽快的回复你。