이벤트관련 메소드
메소드 설 명
bind(type, data, fn, map) 매치돤 요소에 이벤트처리기를 바인딩한다
type : 이벤트종류, data: fn의 파라미터값,
Version3.0 deprecated ,Use the on() method
map: {event:function, event:function, ...}
unbind(type, fn) 매치돤 요소에 이벤트 처리기를 제거한다
Version3.0 deprecated
Use the off() method instead
one(type, data, fn) bind()와 같지만 이벤트를 한번만 실행하고 자동으로 이벤트를 제거한다
trigger(type) 매치된 요소에 대하여 이벤트 타입에 해당하는 이벤트 처리기를 모두 실행한다
type에 사용자 정의 이벤트 가 올 수 있다
$("button").click(function(){
$("p").trigger("myOwnEvent", ["Anja"]);
});
$("p").on("myOwnEvent", function(event, showName){
$(this).text(showName + "! What a beautiful name!").show();
});
메소드 설 명
delegate(selector, type, data, fn) 매치돤 요소에 이벤트처리기를 바인딩한다
동적으로 작성된 새로운 요소에서도 이벤트실행
type : 이벤트종류, data:fn의 파라미터값,
Version3.0 deprecated
Use the on() method instead
undegate(selector, type, data, fn) 매치돤 요소에 이벤트 처리기를 제거한다
Version3.0 deprecated
Use the off() method instead
on(type, data, fn, map )
on(type, selector, data, fn, map ) 매치돤 요소에 이벤트처리기를 바인딩한다
bind 와 delegate 방식
map: {event:function, event:function, ...}
$("p").on({
mouseover: function(){ $("body").css("background-color", "lightgray"); },
mouseout: function(){ $("body").css("background-color", "lightblue"); },
click: function(){ $("body").css("background-color", "yellow"); }
});
메소드 설 명
on(type, data, fn, map )
on(type, selector, data, fn, map ) 매치돤 요소에 이벤트처리기를 바인딩한다
bind 와 delegate 방식
type 에 사용자정의 이벤트 첨부
$("p").on("mouseover mouseout", function(){
$(this).toggleClass("intro");
});
$("p").on("myOwnEvent", function(event, showName){
$(this).text(showName + "! What a beautiful name!").show();
});
off(event, selector, fn) 매치돤 요소에 이벤트처리기를 제거한다
bind형식 - 기존에 미리 만들어진 요소만 이벤트 핸들러가 적용됨
delegate형식 - 기존의 미리 만들어진 요소뿐만 아니라
새롭게 생성되는 요소에도 똑같은 이벤트 핸들러가 적용되어 실행된다
=> bind형식 - on / delegate형식 - on(selector포함)
delegate
bind()메소드는 선택자로 검색한 모든 엘리먼트에 핸들러를 등록한다
$(‘h1’)의 검색 결과가 몇개이는가에 상관없이 문서내의 모든 <h1>엘리먼트에 똑같은 핸들러가 등록 된다
이벤트핸들러 => function 안에서 수행되는 이벤트
그러나 새로 추가되는 엘리먼트에는 핸들러가 지정되지 않아 이벤트가 발생해도 핸들러가 호출되지 않는다 .
미래에 추가될 엘리먼트에 대해서도 핸들러를 미리 등록하는 메서드가 필요
- $(document).delegate(선택자, 이벤트명, 핸들러 );
특정 엘리먼트에 대해 핸들러를 지금 당장 등록하는 것이 아니라
문서가 변경될때마다 핸들러가 등록되어야 하므로 document수준에서 메소드를 호출한다
(document 는 이벤트 대상객체의 부모가 될 수 있다)
- 이벤트 대상은 but
이처럼 실행중에 자동으로 등록되는 살아았는 핸들러를 라이브 핸들러 라고 한다 .
version 3.0에서 모든 이벤트 등록 메소드를 통합하는 메소드가 새로 도입
: on(이벤트명, [선택자], 핸들러) off( 이벤트명, [선택자], 핸들러)
선택자 가 있으면 delegate와 같고 없으면 bind와 같다
AJAX(Asynchronous JavaScript and XML)는 서버와 데이터를 교환하는 기술의 하나
자바스크립트를 이용해서 비동기적으로 서버와 브라우저가 데이터를 주고 받는 방식을 의미한다.
전체 페이지를 다시 로드 하지 않고도 웹 페이지의 일부를 업데이트 할 수 있습니다.(비동기 이용시)
동기 - 요청과 응답이 1:1로 같이 가는 것(요청이 오면 응답이 와야 다음 일을 할 수 있음)
비동기 - 요청과 응답이 따로 가는 것(응답받지 않아도 다음 일을 할 수 있음)
한페이지에 결과를 출력하고 싶은 경우 - Ajax 사용
페이지가 넘어가서 다른 페이지에 결과를 출력할 경우 - Ajax사용불가
JSON(JavaScript Object Notation)은 텍스트-기반의 데이터 교환 형식
JSON은 자바 스크립트 언어에서 유래
JSON 형식은 Douglas Crockford에 의하여 처음으로 지정되었으며, RFC 4627에 기술
공식적인 인터넷 미디어 타입은 application/json이며 파일 이름 확장자는 .json
json 형식
Json object
{ “name” : “홍길동”, “addr” : “대전”, “tel” : “010-1234-5678”}
배열
[“홍길동”, “개나리”,”진달래”, “이도령” ]
Json object 배열
[
{ “name” : “aaa”, “addr” : “대전”, “tel” : “010-1234-5678”},
{ “name” : “bbb”, “addr” : “서울”, “tel” : “010-6789-3456”},
{ “name” : “kkk”, “addr” : “부산”, “tel” : “010-8900-3421”}
]
JSON은 { }안에 이름:value, 이름:value 형식으로 온다.
jQuery를 이용한 AJAX
Ajax를 이용해서 서버에 데이타를 보낼때는 Ajax요청으로 전송 할 수 있고
서버가 이해 할 수 있는 형식으로 바꿔야함
데이타를 직렬화하면 하나의 객체로 모을 수 있고 따라서 Ajax요청에서
데이타를 한덩어리로 보낼 수 있습니다.
<script src="../js/jquery.serializejson.min.js"></script>추가
<form id="my_form">
<input type="text" name=“name" value=“korea" />
<input type="text" name=“kor" value=“82" />
<input type="text" name=“eng" value=“73" />
$("#my_form"). serialize() : 모든 필드를 문자열 하나로 합침
name=korea&kor=82&eng=73
$("#my_form"). serializeArray() : [ {name:“name", value:“korera" },
{name:“kor", value:“82"} , {name:“eng", value=“73" } ]
$("#my_form"). serializeJSON() :
Object {name: “korea", kor: "78", eng: "67", mat: "56", com: "78"}
$('#execute').click(function(){
$.ajax({
url: './time2.jsp',
type:'post',
data:$('form').serialize(),
success:function(data){
$('#time').text(data);
}
}),
error: function(){ },
dataType : json
})
data : 서버로 데이터를 전송할 때 사용한다.
dataType
서버측에서 전송한 응답데이터를 어떤 형식의 데이터로 해석할 것인가를 지정한다. 값으로 올 수 있는 것은 xml, json, script, html이다.
success
성공했을 때 호출할 콜백을 지정한다.
function( PlainObject result, String textStatus, jqXHR jqXHR
type
데이터를 전송하는 방법을 지정한다. get, post를 사용할 수 있다.
error
실패 했을 때 호출할 콜백을 지정한다
function(jqXHR xhr, String status, String error)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/mystyle.css" type="text/css">
<script src="../js/jquery-3.6.0.min.js"></script>
<script>
$(function(){
// $('.but').click(function(){})
// $('.but').bind('click', function(){}) 이 function을 이벤트 핸들러라고 함
// $('.but').one('click', function(){ //one은 딱 한번만 실행할 때 사용, off가 없어도 자동으로 해제됨
$('.but').on('click', function(){
//새로운 버튼을 생성
nbut = $('<button class="but" type="button">확인</button>');
//result1에 추가 - append appendTo
nbut.appendTo($('#result1'));
})
//해제 버튼 - but의 클릭 이벤트를 해제
$('#clear').bind('click', function(){
$('.but').off('click');
//$('.but').unbind('click');//deprecated 됨
})
})
</script>
</head>
<body>
<div class="box">
<br>
<div class="cd">
<button class="but" type="button">확인</button>
</div>
<button type="button" id="clear">해제</button>
<div class="cd" id="result1"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/mystyle.css" type="text/css">
<script src="../js/jquery-3.6.0.min.js"></script>
<script>
$(function(){
// $(document).delegate('.but', 'click', function(){})
// $(document).on('.but', 'click', function(){})//위와 아래는 같음
$('.cd').on('click', '.but', function(){
nbut = $('<button class="but" type="button">확인</button>');
$('#result1').append(nbut);
})
$('#clear').on('click', function(){
$('.cd').off('click');
//$(document).undelegate('click');
})
})
</script>
</head>
<body>
<div class="box">
delegate :<br>
$(document).delegate('.but', 'click', function(){})<br>
$('.cd').on('click', '.but', function(){ })<br>
기존의 미리 만들어진 요소뿐만 아니라<br>
새롭게 생성되는 요소에도 똑같은 이벤트 핸들러가 적용되어 실행된다<br>
document 대신 이벤트 대상의 부모요소가 올 수 있다.<br>
<br>
<div class="cd">
<button class="but" type="button">확인</button>
</div>
<button type="button" id="clear">해제</button>
<div class="cd" id="result1"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/mystyle.css" type="text/css">
<script src="../js/jquery-3.6.0.min.js"></script>
<script>
$(function(){
$('#sync').on('submit', function(){ //bind형식 - 실행하기 전에 미리 만들어놓았기 때문에 둘다(bind,delegate)가능
// //입력한 값 가져오기
// idvalue = $('#id').val();
// passvalue = $('#pass').val();
// namevalue = $('#name').val();
// telvalue = $('#tel').val();
// //서버로 보내기 - post
// $('form').attr('action', 'ajaxTest.jsp');
// $('form').attr('method', 'post');
// $('form').attr({'action':'ajaxTest.jst',
// 'method': 'post'});
$('form').submit();
})
$('#gasync').on('click', function(){
//입력한 값 가져오기
idval = $('#gid').val(); //document.getElementById('gid').value;와 같음
passval = $('#gpass').val();
nameval = $('#gname').val();
telval = $('#gtel').val();
//서버로 보내기 - ajax를 사용하는 비동기방식 - get
//요청 객체 생성
xhr = new XMLHttpRequest(); //브라우저만 있으면 어디든 사용 가능
xhr.open("get","ajaxTest.jsp?id=" + idval +
"&pass=" + passval +
"&name=" + nameval +
"&tel=" + telval ,true); //true일 때 비동기
xhr.send();
//응답 - 서버로부터 실행 결과를 받는다 - result2에 출력
xhr.onreadystatechange = function(){
//readyState : 0,1,2,3,4 4번은 전송완료
//status: 200, 300~ 400~ 500 (200 : 성공 / 300 : 접근오류 / 400 : 요청오류 / 500 : 코딩오류)
if(this.readyState == 4 && this.status == 200){//응답객체
$('#result2').html(this.responseText);
}
}
})
$('#pasync').on('click',function(){
//입력한 값 가져오기
idval = $('#pid').val(); //document.getElementById('gid').value;와 같음
passval = $('#ppass').val();
nameval = $('#pname').val();
telval = $('#ptel').val();
console
xhr = new XMLHttpRequest();
//요청
xhr.open("post", "ajaxTest.jsp", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("id=" + idval + "&pass=" + passval + "&name=" + nameval + "&tel=" + telval);
//응답
xhr.onreadystatechange = function(){
alert(this.readyState);
if(this.readyState == 4 && this.status == 200){
text = this.responseText;
$('#result3').html(text);
}
}
})
})
</script>
</head>
<body>
<div class="box">
동기방식 : 전송하고 서버에서 실행된 결과를 새로운 페이지로 출력<br>
ajax사용하지 않는 방식<br>
<form action="ajaxTest.jsp" method="post">
아이디<input type="text" id="id" name="id"><br>
비밀번호<input type="password" id="pass" name="pass"><br>
이름<input type="text" id="name" name="name"><br>
전화번호<input type="text" id="tel" name="tel"><br>
<button id="sync" type="submit">동기</button>
</form>
<br>
<div id="result1"></div>
</div>
<div class="box">
비동기방식 - get : 전송하고 서버에서 실행된 결과를 새로운 페이지가 아닌
현재 페이지의 result2에 출력
<form>
아이디<input type="text" id="gid" name="id"><br>
비밀번호<input type="password" id="gpass" name="pass"><br>
이름<input type="text" id="gname" name="name"><br>
전화번호<input type="text" id="gtel" name="tel"><br>
<button id="gasync" type="button">비동기 get</button>
</form>
<br>
<div id="result2"></div>
</div>
<div class="box">
비동기방식 - post : 전송하고 서버에서 실행된 결과를 새로운 페이지가 아닌
현재 페이지의 result3에 출력
<form>
아이디<input type="text" id="pid" name="id"><br>
비밀번호<input type="password" id="ppass" name="pass"><br>
이름<input type="text" id="pname" name="name"><br>
전화번호<input type="text" id="ptel" name="tel"><br>
</form>
<br>
<button id="pasync" type="button">비동기 post</button>
<div id="result3"></div>
</div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
table{
border : 2px solid blue;
border-collapse: collapse;
}
td{
width: 200px;
height: 50px;
text-align: center;
}
</style>
</head>
<body>
Hello
<%
//자바문장 기술
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("id");
String userPass = request.getParameter("pass");
String userName = request.getParameter("name");
String userTel = request.getParameter("tel");
%>
<table border="1">
<tr>
<td>아이디</td>
<td><%= userId %></td>
</tr>
<tr>
<td>이름</td>
<td><%= userName %></td>
</tr>
<tr>
<td>전화번호</td>
<td><%= userTel %></td>
</tr>
</table>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/mystyle.css" type="text/css">
<script src="../js/jquery-3.6.0.min.js"></script>
<script>
const xhr = new XMLHttpRequest();
$(function(){
$('#text').on('click', function(){
//요청
xhr.open('get', 'text.jsp', true)
xhr.send()
//응답
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
txt = this.responseText;
//홍길동/개나리/진달래/무궁화/삼천리/금수강산
arr = txt.split("/");
console.log(arr);
//for(i=0; i<arr.length;i++) for문으로 쓸 때
str = "";
$.each(arr,function(i){
str += arr[i] + "<br>";
})
$('#result1').html(str);
}
}
})
$('#jobj').on('click', function(){
xhr.open('get', 'jobj.jsp', true)
xhr.send()
//응답
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
txt = this.responseText;
}
})
})
</script>
</head>
<body>
<div class="box">
<br>
<br>
<button id="text" type="button">text</button>
<button id="jobj" type="button">jsonObject</button>
<button id="jarr" type="button">jsonArray</button>
<button id="obarr" type="button">objectArr</button>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
<div id="result4"></div>
</div>
</body>
</html>