국비 57일차 jQuery ( 각종 event처리 , ajax - get, post, json)
2021. 3. 30. 18:22
2021.03.30 국비교육 57일차
[TOC]
Event
select
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#test").on("change", function(){
console.log($(this).val());
$("#result").text($("#test").val());
})
})
</script>
</head>
<body>
<select id = "test">
<option>a</option>
<option>b</option>
</select>
<span id ="result"></span>
</body>
</html>
on
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").on("click mouseover", function(){
console.log("ok");
console.log(event.screenX, event.screenY);
$("#result").text(event.screenX);
})
$("#b").on("click", function(){
$("#a").off("click mouseover"); //이벤트제거
})
})
</script>
</head>
<body>
<button id ="a">ok</button>
<button id ="b">cancel</button>
<div id = "result"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").on("click", function(){
$("div").html("<button id = 'newbutton'>oktest</button>");
})
$("body").on("click", "#newbutton", function(){ //click 하면 newbutton 찾아가서 이벤트 전달
console.log("======")
})
})
</script>
</head>
<body>
<button id ="a">ok</button>
<div></div>
</body>
</html>
one
- 이벤트처리 딱 한번만
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").one("click", function(){
console.log("ok");
})
})
</script>
</head>
<body>
<button id ="a">ok</button>
</body>
</html>
trigger
- 다른 이벤트 강제 실행
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").on("click mouseover", function(){
console.log("ok");
})
$("#b").on("click", function(){
console.log("trigger on");
$("#a").trigger("click"); //다른 이벤트 강제 실행
})
})
</script>
</head>
<body>
<button id ="a">ok</button>
<button id ="b">ok-trigger</button>
</body>
</html>
form 처리
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#myForm1").on("submit", function(){
console.log("submit");
$("#myForm1").attr("action", "target_1.html");
//event.preventDefault(); //action 실행 금지
//return false; //함수 멈춤
})
$("#b").on("click", function(){
event.preventDefault();
//$("#myForm2").attr("action", "target_1.html");
console.log("b실행")
//event.preventDefault(); //action 실행 금지
//return false; //함수 멈춤
})
})
</script>
</head>
<body>
<form id = "myForm1" action ="target.html">
<button id = "a">a</button> <br>
<input type = "submit" value = "전송">
</form>
<hr>
<form id = "myForm2" action ="target.html">
<button id = "b">b</button> <br>
</form>
</body>
</html>
event_parameter
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").on("click", {foo : "aaa", test:"abc"}, function(event){
console.log(event.data.foo);
console.log(event.data.test);
})
})
</script>
</head>
<body>
<button id ="a">ok</button>
<div></div>
</body>
</html>
Event 심화
click
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//$("#a").on("click", fn)과 동일
$("#a").click(function(){
console.log("ok");
});
$("#b").click(function(){
$("#a").click(); //trigger("click")과 동일
});
})
</script>
</head>
<body>
<button id = "a">ok</button>
<button id="b">ok-trigger</button>
<div id="result"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("div").click(function(){
console.log($(this).text());
$("#result").html("<h1>" + $(this).text() + "</h1>")
})
})
</script>
</head>
<body>
<div>홍길동</div>
<div>이순신</div>
<div>유관순</div>
<span id="result"></span>
</body>
</html>
submit
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//$("form").on("submit", xxx); // xxx = 핸들러 함수
$("form").submit(xxx);
})
function xxx(){
if($("#userid").val().length ==0){
alert("아이디를 입력하세요");
event.preventDefault();
}
}
</script>
</head>
<body>
<form action="sample01_click.html">
아이디:<input type="text" name="userid" id="userid"><br>
<input type="submit" value="로그인">
</form>
</body>
</html>
focus
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#target").on("focus", function(){
console.log("target focus");
$(this).css("background", "yellow");
})
$("#target").on("blur", function(){
console.log("target blur");
$(this).css("background", "");
}) //blur 이벤트 , text칸 색 사라짐
$("#other").on("click", function(){
console.log("other focus");
$("#target").trigger("focus");
})
$("#other2").on("click", function(){
console.log("other2 blur");
$("#target").blur();
})
$("#other3").on("click", function(){
console.log("other3");
$("#target").off("blur focus");
})
})
</script>
</head>
<body>
<form >
<input type="text" id="target">
<input type="text" >
</form>
<button id="other">focus</button>
<button id="other2">blur</button>
<button id="other3">clear</button>
</body>
</html>
change
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
/*$(" #sweets").on("change", function(){
var data = $(this).val();
$("#result").text(data);
}) */
$("#sweets").change(function(){
var data = $(this).val();
$("#result").text(data);
})
})
</script>
</head>
<body>
<form >
<select id="sweets">
<option value="aa" selected="selected">사탕</option>
<option value="bb" >아이스크림</option>
<option value="cc" >쿠키</option>
</select>
</form>
<div id = "result"></div>
</body>
</html>
keydown
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#test").keydown(function(){ //keydown 클릭하면 발생
$("#result").text(event.keyCode); //keyCode 발생
})
})
</script>
</head>
<body>
<p>keydown 실습 </p>
<input type="text" id="test">
<div id="result"></div>
</body>
</html>
mouseEnter / mouseleave
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#outer").mouseenter(function() {
$("#log").append("<div>mouseEnter발생</div>");
});
})
</script>
</head>
<body>
<div id="outer">
outer
<div id="inner">inner</div>
</div>
<div id="log"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//mouseover와는 다르게 자식요소에서는 발생되지 않음
$("#outer").mouseleave(function() {
$("#log").append("<div>mouseEnter발생</div>");
});
})
</script>
</head>
<body>
<div id="outer">
outer
<div id="inner">inner</div>
</div>
<div id="log"></div>
</body>
</html>
hover
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("li").hover(
function(){
$(this).append("<span>***</span>");
}, //funtion1
function(){
$(this).find("span").remove();
} //function 2
); //hover
})
</script>
</head>
<body>
<ul>
<li>홍길동</li>
<li>이순신</li>
<li class="fade">유관순</li>
<li class="fade">강감찬</li>
</ul>
</body>
</html>
check (each 활용)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#test").click(function(){
/* var data = $(".fruit");
var mgs = "";
for(var i=0; i<data.length;i++){
if(data[i].checked){
mgs += data[i].value;
}
}
$("#result").text(mgs); */
/* var mesg = "";
$.each($(".fruit"), function(idx, ele){
if(ele.checked){
mesg += ele.value;
}
})
$("#result").text(mesg); */
var mesg = "";
$(".fruit").each(function(idx, ele){
if(ele.checked){
mesg += ele.value;
}
})
$("#result").text(mesg);
})
})
</script>
</head>
<body>
<input type = "checkbox" class = "fruit" value = "사과">사과
<input type = "checkbox" class = "fruit" value = "배">배
<input type = "checkbox" class = "fruit" value = "귤">귤
<button id = "test">확인</button>
<div id = "result"></div>
</body>
</html>
hide / show
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
//애니메이션 효과
$(function() {
$("#hider").click(function(){
$("span").hide("slow"); //감추기
})
$("#shower").click(function(){
$("span").show(2000, function(){ //ms, fn
$("#red").css("font-size", "30px");
})
})
})
</script>
</head>
<body>
<button id="hider">Hide</button>
<button id="shower">show</button>
<div>
<span>이성계</span><span>이순신</span>
<span>강감찬</span><span>윤봉길</span>
<span>정몽주</span><span id="red">위인들</span>
</div>
</body>
</html>
toggle
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
//toggle 대상요소를 숨기거나 보여주는 효과를 번갈아 함
$(function() {
$("#toggler").click(function(){
$("#red").toggle("slow");
})
})
</script>
</head>
<body>
<button id="toggler">toggle</button>
<div>
<span>이성계</span><span>이순신</span>
<span>강감찬</span><span>윤봉길</span>
<span>정몽주</span><span id="red">위인들</span>
</div>
</body>
</html>
fadeIn
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
#one{
background : blue;
border : 1px solid blue;
width : 70px;
height :70px;
margin : 0 3px;
float : left;
}
#two{
background : red;
border : 1px solid blue;
width : 70px;
height :70px;
margin : 0 3px;
float : left;
}
#three{
background : green;
border : 1px solid blue;
width : 70px;
height :70px;
margin : 0 3px;
float : left;
}
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
//toggle 대상요소를 숨기거나 보여주는 효과를 번갈아 함
$(function() {
$("span").click(function(){
$("div:hidden:first").fadeIn("slow");
})
})
</script>
</head>
<body>
<span> click here </span>
<div id="one" style="display:none;"></div>
<div id="two" style="display:none;"></div>
<div id="three" style="display:none;"></div>
</body>
</html>
fadeToggle
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
#one{
background : blue;
border : 1px solid blue;
width : 70px;
height :70px;
margin : 0 3px;
float : left;
}
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("span").click(function(){
$("#one").fadeToggle("slow");
})
})
</script>
</head>
<body>
<span> click here </span>
<div id="one"></div>
</body>
</html>
fadeTo
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("p:first").click(function(){
$(this).fadeTo("slow", 0.33); // 뒤의 숫자 = 투명도
})
$(".my").click(function(){
$(this).fadeTo("slow", 0.55);
})
$("p:last").click(function(){
$(this).fadeTo("slow", 0.55);
})
})
</script>
</head>
<body>
<p>홍길동</p>
<p class = "my">이순신</p>
</body>
</html>
slideUp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("button").click(function(){
$(this).parent().slideUp("slow", function(){
$("#msg").text($(this).text() + "완료됨");
});
});
})
</script>
</head>
<body>
<div>
<button>Hide one</button>
<input type="text" value="one">
</div>
<div>
<button>Hide two</button>
<input type="text" value="two">
</div>
<div>
<button>Hide three</button>
<input type="text" value="three">
</div>
<div id="msg"> </div>
</body>
</html>
slideDown
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
div{
background : blue;
border : 1px solid blue;
width : 70px;
height :70px;
margin : 0 3px;
float : left;
}
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document.body).click(function(){
if($("div:first").is(":hidden")){
$("div").slideDown("slow");
}else{
$("div").hide();
}
});
})
</script>
</head>
<body>
Click me
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
Ajax
기본 처리 방식
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").click(getData);
})
function getData(){
alert("getData 호출");
$.ajax(
{
type : "get", //1. client => 서버로 보내지는 request방식 get 방식 요청
url : "sample01_text.jsp", //2. 요청을 처리할 위치
dataType : "text", //응답타입 //3. 응답(response)에 대한 데이터 형 text, json, xml
success : function(data, status, xhr){ //4-1 정상 응답이 이루어진 경우 //status 200(처리성공)
//data : 서버에 응답한 데이터, status(응답 상태값), XMLHttpRequest 객체
$("#result").text(data);
},
error : function(xhr, status, e){ //4-2 응답 실패한 경우(문제 발생) 404,500....
//xhr : XMLHttpRequest, status(응답상태값), e(에러메세지)
console.log("error", e);
console.log("status", status);
}
}
); //end ajax
} //end function
</script>
</head>
<body>
<button id = "a">ajax 요청</button>
<div id = "result"></div>
</body>
</html>
데이터 전송 및 반환 방식
- ajax에 json형태로 보내준 다음에 jsp에서는 getparameter로 받아줘야함
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").click(getData);
})
function getData(){
alert("getData 호출");
$.ajax(
{
type : "get", //1. client => 서버로 보내지는 request방식 get 방식 요청
url : "sample01_text.jsp", //2. 요청을 처리할 위치
dataType : "text", //응답타입 //3. 응답(response)에 대한 데이터 형 text, json, xml
success : function(data, status, xhr){ //4-1 정상 응답이 이루어진 경우 //status 200(처리성공)
//data : 서버에 응답한 데이터, status(응답 상태값), XMLHttpRequest 객체
$("#result").text(data);
},
error : function(xhr, status, e){ //4-2 응답 실패한 경우(문제 발생) 404,500....
//xhr : XMLHttpRequest, status(응답상태값), e(에러메세지)
console.log("error", e);
console.log("status", status);
}
}
); //end ajax
} //end function
</script>
</head>
<body>
<button id = "a">ajax 요청</button>
<div id = "result"></div>
</body>
</html>
POST방식
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").click(setData);
})
function setData(){
alert("setData 호출");
$.ajax(
{
type : "post",
url : "sample01_text2.jsp",
//contentType :"application/x-www-form-urlencoded; charset = UTF-8",
data : { //json 형태로 보냄
v1 : $("#v1").val(),
v2 : $("#v2").val()
},
dataType : "text",
success : function(data, status, xhr){
$("#result").text(data);
},
error : function(xhr, status, e){
console.log("error", e);
console.log("status", status);
}
}
); //end ajax
} //end function
</script>
</head>
<body>
<button id = "a">ajax 요청</button><br>
v1 <input type = "text" name = "v1" id = "v1"><br>
v2 <input type = "text" name = "v2" id = "v2">
<div id = "result"></div>
</body>
</html>
JSON 방식
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#a").click(function(){
alert("getData 호출");
$.ajax(
{
type : "get",
url : "sample02_json.jsp",
dataType : "json",
success : function(data, status, xhr){
var username = data.username;
var age = data.age;
$("#result").text(username + ":" + age);
},
error : function(xhr, status, e){
console.log("error", e);
console.log("status", status);
}
}
); //end ajax
});
})
</script>
</head>
<body>
<button id = "a">ajax 요청</button><br>
<div id = "result"></div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String name = "홍길동";
int age = 20;
%>
{
"username" : "<%=name %>",
"age" : "<%=age %>"
}
'ETC > 국비교육' 카테고리의 다른 글
국비 56일차 jQuery(traverse, 속성값 추출, manipulation, utility) (0) | 2021.03.29 |
---|---|
국비 55일차 jQuery (기본선택자, 계층구조, 속성, filter, contain, has, empty) (0) | 2021.03.26 |
국비 54일차 jQuery 기본 표현식 (0) | 2021.03.25 |
국비 52일차 session관리 (0) | 2021.03.24 |
국비 51일차 (MVC패턴, hidden활용, Map과 List) (0) | 2021.03.22 |