jQuery Ajax 跨域前端实现登录

封装好的请求对象

(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')
	})
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值