본문 바로가기

Programming Languages/JavaScript

[ JavaScript ] 자바스크립트 AJAX 송수신

<html>
<head>

function sendAjaxData
(
	url, 
	data = null, 
	method = "POST", 
	async = true, 
	timeout = 3000, 
	callbackFunc = null
)
{
	let requestId = url.split('?')[0].split('/').reverse()[0].replace('.do','');

	let xhr	= new XMLHttpRequest();

	if(async)
	{
		xhr.timeout = timeout;	
	}

	xhr.open(method, url, async);

	if(data != null)
	{
		if(data.toString() == '[object FormData]')
		{
		}
		else if
		(
			typeof data == 'object' && 
			data.length == undefined && 
			Object.keys(data).length >= 1
		)
		{
			xhr.setRequestHeader('Content-Type', 'application/json');
		
			data = JSON.stringify(data);
		}
		else
		{
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
	}

	xhr.setRequestHeader('Ajax-Yn', 'Y');

	xhr.onreadystatechange = function() 
	{
		if(xhr.readyState === XMLHttpRequest.DONE) 
		{
			let responseId = xhr.responseURL.split(location.host).reverse()[0].split('?')[0].split('/').reverse()[0].replace('.do','');

			if (xhr === 0 || (xhr.status >= 200 && xhr.status < 400)) 
			{
				if(callbackFunc == null)
				{
					callbackFunc = callback_ajax;
				}

				if(typeof callbackFunc !== 'function')
				{
					alert('callback_ajax(requestId, result, errorFlag, requestUrl, requestData, responseId) 함수가 구현되어 있지 않습니다.');
					return;
				}
				
				callbackFunc(requestId, xhr.responseText, false, url, data, responseId);
			}
			else	
			{
				callbackFunc(requestId, "에러코드[" + xhr.status + "]가 발생하였습니다.", true, url, data, responseId);
			}
		}
	};

	xhr.ontimeout = function() 
	{
		let responseId = xhr.responseURL.split(location.host).reverse()[0].split('?')[0].split('/').reverse()[0].replace('.do','');

		callbackFunc(requestId, "타임아웃 처리되었습니다.", true, url, data, responseId);
	};

	xhr.send(data);
}

function doLogin(form)
{
	url = "/doLogin.do";

	sendAjaxData
	(
		url
		, new FormData(form)
		, "POST"
		, true
		, 3000
		, 
		function
		(
			requestId, 
			result, 
			errorFlag, 
			requestUrl, 
			requestData, 
			responseId
		)
		{
			result = JSON.parse(result);

			if(result.result == "success")
			{
				window.location.reload();
			}
		}
	);
}

</head>
<body>
	<form method="post" onSubmit="return doLogin(this);">
	<input type="text" name="id" value="아이디를 입력하세요" />
	<input type="password" name="pw" value="비밀번호를 입력하세요" />
	<input type="submit" value="등록" />
</body>
</html>