封装好的请求对象
(function() {
var ajax = {
ajax_cors: function(url, data, fn, dataType, contentType) {
$.ajaxSetup({
type: 'post',
dataType: dataType == null ? 'json' : dataType,
global: true,
contentType: contentType == null ? 'application / x - www - form - urlencoded' : contentType,
success: function(xhr, status, success) {
console.log('请求成功! ' + '当前状态 ' + status)
console.log('响应体: ' + JSON.stringify(success))
fn(xhr, status, success.data)
},
error: function(xhr, status, error) {
console.log('请求失败! ' + '当前状态 ' + status)
console.log('响应体: ' + JSON.stringify(error))
fn(xhr, status, data)
},
xhrFields: {
withCredentials: true
},
crossDomain: false,
beforeSend: function(xhr) {
console.log('正在发送请求: url => ' + url)
console.log('发送数据类型: ' + this.contentType)
console.log('当前发送数据: ' + this.data)
},
complete: function(xhr, status) {
console.log('请求已经完成')
console.log('响应类型: ' + this.dataType)
},
cache: false,
timeout: 3000,
})
$.ajax({
url: url,
data: data,
})
}
}
window.$kongjs = ajax;
})()
具体代码,跨域通过验证码登录
$(function() {
var imageUrl = 'http://127.0.0.1:8080/user?method=doYanCode';
var bool = true;
if (bool) {
$('#imageCode').attr('src', imageUrl);
}
$('#imageCode').click(function() {
bool = false
$kongjs.ajax_cors("http://127.0.0.1:8080/user?method=doYanCode", {}, function(data) {
$('#imageCode').attr("src", imageUrl)
console.log(data)
}, '*')
})
$('#submit').click(function() {
var formData = $("#loginForm").serialize();
$kongjs.ajax_cors("http://127.0.0.1:8080/user?"+formData,{'Access-Control-Ajax-Headers': 'cors'}, function(data) {
console.log(data)
if (data.code == 1) {
// 调整到首页
location.href = "/web/index.html";
} else {
console.log(data.message);
}
}, '*','json')
})
})