jQuery Ajax 跨域前端實現登入

孔德昌發表於2021-01-02

封裝好的請求物件

(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, 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')
	})
})

相關文章