본문 바로가기

기록/자바_국비

[배운내용정리] 0128 자바 국비교육_ jQuery_ajax

728x90

2021년 01월 28일 9시 ~ 15시 30분 zoom으로 수업 진행

 


 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style type="text/css">
        div {
            border: 2px solid red;
            width: 200px;
            padding: 10px;
        }
        p {
            background-color: orange;
        }
        h1 {
            border: 1px solid blue;
        }
    </style>

    <script type="text/javascript" src="js/jquery-3.5.1.js"></script>
    <script type="text/javascript">
        $(function() {
            $("p:eq(0)").click(function() {
                $(this).remove();//누르면 해당 p태그가 사라진다.
            });

            $("p:eq(1)").click(function() {
                $(this).empty();//누르면 해당 p태그의 내용이 비워진다.
                //$(this).parent().empty();//div태그 안에 들어있는 내용이 전부 비워진다.
            });

            $("p:eq(2)").click(function() {
                var ele = $(this).detach();//누르면 해당 p태그가 사라지고 ele 변수에 담기게 된다.
                console.log(ele);

                $("h1").append(ele);//h1태그 안에 ele 변수에 담긴 p태그가 들어간다.
            });

        });
    </script>

</head>
<body>
    <h1>엘리먼트 제거하가</h1>
    <div>
        <p>remove</p>
        <p>empty</p>
        <p>detach</p>
    </div>
    
</body>
</html>

 


 

ajax 시작

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
	* {
		margin: 0px;
		padding: 0px;
	}
	table {
		width:400px;
	}
	table tr:nth-child(odd) {
		background-color: orange;
	}
	fieldset {
		width:400px;
	}
	body {
		width:1000px;
		margin:50px;
	}
</style>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
	$(function() {
		$("#emp_search").click(function() {
			var empId = $("input[name=empId]").val();
			
			if(!isNaN(empId) && empId.length > 2) {
				$.ajax({
					url:"emplist.xml", 		//전송(통신)할 페이지 주소
					method:"get", 			//서버에 전송하는 방식
					dataType:"xml",			//전송받을 데이터 타입(xml, json, script, ....)
					//data:{id:"menuId"}, 	//서버에 전송할 데이터
					success:function(data) {//통신에 성공했을 때 실행
						var empInfo = $(data).find("EMPLOYEE_ID:contains(" + empId +")").parent();//찾는 사원번호가 담겨있는 행 가져오기
						
						if( (empInfo).is("ROW") ) {
							$("table input").each(function(i) {
								$(this).val( $(empInfo).children().eq(i).text() );
							});
						}
						else {
							alert("검색대상이 존재하지 않습니다.");
						}
						
					},
					error:function() {		//통신에 실패했을 때 실행
						alert("실패");				
					}
					
				});
			}
			else {
				alert("사원번호를 제대로 입력해주세요");
			}
		});
	});
</script>

</head>
<body>
	<h1>데이터 가져오기</h1>
	
	<!--  ajax : Asyncronous Javascript And Xml -->
	<fieldset>
		<legend>사원 정보 조회</legend>
		<input type="text" name="empId">
		<input type="button" id="emp_search" value="조회">
	</fieldset>
	
	<table>
		<tr>
			<th>사원번호</th>
			<td> <input type="text" name="empNum"> </td>
		</tr>
		<tr>
			<th>이&nbsp;름</th>
			<td> <input type="text" name="empName"> </td>
		</tr>
		<tr>
			<th>이 메 일</th>
			<td> <input type="text" name="empEmail"> </td>
		</tr>
		<tr>
			<th>전화번호</th>
			<td> <input type="text" name="empPhone"> </td>
		</tr>
		<tr>
			<th>입 사 일</th>
			<td> <input type="text" name="empHire"> </td>
		</tr>
	</table>
	
	
	
</body>
</html>

 


 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
	* {
		margin: 0px;
		padding: 0px;
	}
	table {
		width:400px;
	}
	table tr:nth-child(odd) {
		background-color: orange;
	}
	fieldset {
		width:400px;
	}
	body {
		width:1000px;
		margin:50px;
	}
</style>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
	$(function() {
		$("#emp_search").click(function() {
			var empId = $("input[name=empId]").val();
			
			if(!isNaN(empId) && empId.length > 2) {
				$.ajax({
					url:"emplist.xml", 		//전송(통신)할 페이지 주소
					method:"get", 			//서버에 전송하는 방식
					dataType:"xml",			//전송받을 데이터 타입(xml, json, script, ....)
					//data:{id:"menuId"}, 	//서버에 전송할 데이터
					success:function(data) {//통신에 성공했을 때 실행
						var empInfo = $(data).find("EMPLOYEE_ID:contains(" + empId +")").parent();//찾는 사원번호가 담겨있는 행 가져오기
						
						if( (empInfo).is("ROW") ) {
							$("table input").each(function(i) {
								$(this).val( $(empInfo).children().eq(i).text() );
							});
						}
						else {
							alert("검색대상이 존재하지 않습니다.");
						}
						
					},
					error:function() {		//통신에 실패했을 때 실행
						alert("실패");				
					}
					
				});
			}
			else {
				alert("사원번호를 제대로 입력해주세요");
			}
		});
	});
</script>

</head>
<body>
	<h1>데이터 가져오기</h1>
	
	<!--  ajax : Asyncronous Javascript And Xml -->
	<fieldset>
		<legend>사원 정보 조회</legend>
		<input type="text" name="empId">
		<input type="button" id="emp_search" value="조회">
	</fieldset>
	
	<table>
		<tr>
			<th>사원번호</th>
			<td> <input type="text" name="empNum"> </td>
		</tr>
		<tr>
			<th>이&nbsp;름</th>
			<td> <input type="text" name="empName"> </td>
		</tr>
		<tr>
			<th>이 메 일</th>
			<td> <input type="text" name="empEmail"> </td>
		</tr>
		<tr>
			<th>전화번호</th>
			<td> <input type="text" name="empPhone"> </td>
		</tr>
		<tr>
			<th>입 사 일</th>
			<td> <input type="text" name="empHire"> </td>
		</tr>
	</table>
	
	
	
</body>
</html>

 

function makeTable (elem) {
	//elem : emplist.xml의 <ROW>들
	
	$table = $("<table border=1>");
	
	//컬럼 이름 가져오기
	//emplist.xml 에 태그 이름이 EMPLOYEE_ID / LAST_NAME / EMAIL / PHONE_NUMBER / HIRE_DATE 로 되어있음
	for(var i=0; i<1; i++) {
		$tr = $("<tr>");
		
		for(var j=0; j<elem.eq(0).children().length; ++j) {
			$td = $("<th>").append( elem.eq(0).children().eq(j).prop("tagName") );
			$tr.append( $td );
		}
		$table.append($tr);
	}
	
	//데이터 넣기
	for(var i=0; i<elem.length; i++) {
		$tr = $("<tr>");
		for(var j=0; j<elem.eq(0).children().length; ++j) {
			$td = $("<td>").append( elem.eq(i).children().eq(j).text() );
			$tr.append( $td );
		}
		$table.append($tr);
	}
	
	return $table;
	
	
}