TIL_2021.09.27(월) JAVASCRIPT(AJAX) and DB INSERT

개발중·2021년 9월 27일
0

자바스크립트

목록 보기
3/3
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%@ taglib prefix="functions"
	uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>


</head>
<body>

	<div class="container">
		<h2>Ajax Form Insert</h2>
		<form enctype="application/x-www-form-urlencoded" name="frm" id="frm">
			<div class="form-group">
				<label for="name">Name:</label> <input type="text"
					class="form-control" id="name" name="name"
					placeholder="Enter email">
			</div>
			<div class="form-group">
				<label for="email">Email:</label> <input type="email"
					class="form-control" id="email" name="email"
					placeholder="Enter email">
			</div>
			<div class="form-group">
				<label for="pwd">Password:</label> <input type="password"
					class="form-control" id="pwd" name="pwd"
					placeholder="Enter password">
			</div>

			<button type="button" class="btn btn-default">Submit</button>
		</form>
	</div>
	<table>
		<thead>
			<tr>
				<th>NO</th>
				<th>NAME</th>
				<th>EMAIL</th>
				<th>PWD</th>
				<th>REGDATE</th>
			</tr>
		</thead>
		<tbody id="tb">
		</tbody>
	</table>

</body>

<script type="text/javascript">
	function sendAjax(){
		$.ajax({
			url:'/web/ajaxInsert.do?cmd=ajaxInsert',
			type:'POST',
			contentType:'application/x-www-form-urlencoded;charset=UTF-8',
			dataType:'json',
			//data:{name:$("input#name").val(), email:$("input#email").val(), pwd:$("input#pwd").val()},
			data:$("form#frm").serialize(),
			success : function(result) {
				console.log(result);
				$(result).each(function(index,dom){
                	var tr=document.createElement("tr");
                	for(var j in dom){
                		var td=document.createElement("td");
                		td.appendChild(document.createTextNode(dom[j]));
                		tr.appendChild(td);
                	}//for
                   document.getElementById("tb").appendChild(tr);
        
                });
			}
		});
		}
  $(function(){
     $("button").click(function(){
    	sendAjax();
     });
  });

 </script>
</html>

스크립트 태그는 body 밑에 쓰는 것이 좋다는 이야기를 들어 밑에 작성했다.

ajax에서 success:function(result)에서 result가 왜 ajaxEx8Date.jsp의 값이 들어오는 것인지 궁금했는데 검색해 보니 통신에 성공하면 AjaxInject 안의 request.setAttribute("AjaxList", AjaxDao.getMyBatisDao().selectAjax()); 구문을 통해 값을 받아 온다.

[
<c:forEach var="i" items="${AjaxList}" varStatus="cnt">
	{"no":${i.no},
	"name":"${i.name}",
	"email":"${i.email}",
	"pwd":"${i.pwd}",
	"regdate":"${i.regdate}"
	}
<c:choose>
		<c:when test="${fn:length(AjaxList)!=cnt.count}">,</c:when>
	</c:choose>
</c:forEach>
]

또한 JSON으로 값을 넘길 때에는 숫자는 따옴표를 쓰지 않지만 문자열은 따옴표를 꼭 써 주어야 한다. 그리고 자바스크립트는 원래 홑따옴표와 쌍따옴표 둘 다 사용할 수 있지만 JSON에서는 쌍따옴표만 사용하여야 한다.

AJAX 메소드

  1. url : 클라이언트가 요청을 보낼 서버의 url 주소
  2. type : 전송 방식(get or post etc..)
  3. dataType : 서버에 보내 줄 데이터의 타입 (json, text etc..)
  4. data : 서버로 보낼 데이터가 있는 경우 사용
profile
공부한 것 정리하는 개발 입문자

0개의 댓글