본문 바로가기

회고록(TIL&WIL)

TIL 2023.02.07 JSON, jQuery

JSON

  1. 키:값 쌍으로 이루어진 형태
  2. 키 값은 반드시 문자열 형태여야함
  3. "" 만 사용 가능(''은 오류, 이스케이프 문자 사용가능) {"key":"val", "key2":1234}

parsing

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css" rel=stylesheet>
table{
	width:1000px;
	border-collapse: collapse;
}
table,th,td{
	border: 1px solid gray;
}
</style>
<script type="text/javascript">
var table, tbody, xhr;
window.onload = () => {
	table = document.querySelector('table');
	tbody = table.querySelector('tbody');
	xhr = new XMLHttpRequest();
	init();
}
function getList(){
	if(xhr.readyState == 4 && xhr.status == 200){
		var data = xhr.responseText;
		data = JSON.parse(data); // parse - JSON문자열을 JS Object로 변환
// 		data = JSON.stringify(data); // stringfy - JS Object를 JSON문자열로 변환
		var msg = "";
		// 1. 반복문
// 		var arr = data.stu;
// 		for(obj of arr){
// 			console.log(obj.num, obj.name, obj.kor, obj.eng, obj.math);
// 		}
		// 2. forEach
		data.stu.forEach((ele,idx)=>{
// 			console.log(ele.num, ele.name, ele.kor, ele.eng, ele.math);
			msg += "<tr>"
			msg += "<td>"+ele.num+"</td>"
			msg += "<td>"+ele.name+"</td>"
			msg += "<td>"+ele.kor+"</td>"
			msg += "<td>"+ele.eng+"</td>"
			msg += "<td>"+ele.math+"</td>"
			msg += "<tr>"
		});
		tbody.innerHTML = msg;
	}
}
function init(){
	xhr.onreadystatechange = getList;
	xhr.open('get', 'ex01.json');
	xhr.send();
}
</script>
</head>
<body>
<h1>JSON parsing</h1>
<table>
	<thead>
		<tr>
			<th>학번</th>
			<th>이름</th>
			<th>국어</th>
			<th>영어</th>
			<th>수학</th>
		</tr>
	</thead>
	<tbody>
	
	</tbody>
</table>
</body>
</html>

JSP 파일로 JSON 데이터 만들기

JSP page 설정에 contentType=application/json 으로 변경, json데이터는 반드시 맨위부터 작성되어야함

{"emp":[
<%
String driver = "com.mysql.jdbc.Driver";
String url= "jdbc:mysql://localhost:3306/lecture";
Map<String, String> env = System.getenv();
String user = env.get("MYSQL_USER");
String password = env.get("MYSQL_PW");
String sql = "select * from emp";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
	Class.forName(driver);
	conn = DriverManager.getConnection(url, user, password);
	stmt = conn.createStatement();
	rs = stmt.executeQuery(sql);
	while(rs.next()){
		if(!rs.isFirst()) out.print(",");
%>
{
"empno":<%=rs.getInt("empno") %>,
"ename":"<%=rs.getString("ename") %>",
"hiredate":"<%=rs.getString("hiredate") %>",
"sal":<%=rs.getInt("sal") %>,
"comm":<%=rs.getInt("comm") %>
}
<%
	}
} finally{
	if(rs!=null) rs.close();
	if(stmt!=null) stmt.close();
	if(conn!=null) conn.close();
}
%>
]}
<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*, java.sql.*"%>

jQuery

CDN 형식으로 사용할 수 도 있지만 압축된(minified) js파일로 다운받기 가능
최신 3.x ver에선 device에 따라 나눠둠 slim은 mobile용
element가 아닌 jquery 객체를 리턴한다.
체이닝의 장점이 있음
오직 DOM 제어를 편하게 해주는 기능만을 가지고 있음
script 사용 전 다운받은 js파일을 불러와야 jquery를 사용 할 수 있다.

<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>

선택자 - css선택자를 그대로 다 쓸 수 있다.

jQuery('h1');
jQuery('.cl1');
jQuery('#i1');
jQuery('h1+p'); // 다음 p 태그
jQuery('h1~p'); // 이후 p 태그들
jQuery('ul>li:nth-child(2n)');
$==jQuery; // true
$('h1');
$('h1').css('color', 'red');
// traversing
$('h1').next().prev()
$('h2').nextAll().prevAll()
$('h2+p+h2').siblings().css('color', 'red') // 자신을 제외한 나머지
// Tree traversing
$('#i1').parent() // ul
$('ul').children() // li*5
$('#i1').parents() // ul body html
// Filtering
$('li').eq(0).css('color', 'red'); // 0부터
$('li:eq(0)').css('color', 'red'); // 0부터
$('li:nth-child(1)').css('color', 'red'); // 1부터
$('li').first().last() // 처음 끝
$('li').odd().even() // 홀수 짝수 ver 3.5 이후 부터
$('li').filter(":eq(0)")
$('li').filter(":odd") // index 번호가 홀수 :even은 짝수
// Miscellaneous Traversing
$('li').add('h1') // 한번에 처리하기 위해 추가 선택
$('li').not('li:eq(0)') // 제외
// 확장된 selector
$('input[type=text]').css('color','red');
$('input[type=password]').css('color','red');
$('[type=number]').css('color','red');
$(':password').css('color','red');
$(':first').css('color','red');

CSS조정

window.onload = function(){
    // css("attribute", "value") setter
    $('h1').css("color", "red");
    $('h1').css("background-color", "yellow");
    $('h1').css("width", 200); //기본단위 px 외에는 명시적으로
    $('h1').css({width: '300px', height: '60px'});
    var callback = function(idx, val) {
        // return "rgb("+255/8*idx+",255,255)";
        return "rgba(255,0,0,"+idx/7+")";
    };
    $('li').css('background-color', callback);
    // css("attribute") getter
    console.log($('h1').css("color"));
    console.log($('h1').css("height"));
    console.log($('h1').css(["width", "height"]));
}

carousel 만들기

var su = 0, cnt = 1;
window.onload = function(){
    // $('#carousel').css("width", 200 * cnt);
    // setInterval(nextImg, 3000);
    su = -1;
    nextImg();
}
function nextImg(){
    // if(su++ >= 6 - cnt) su = 0;
    // $('ul').css('margin-left', -200 * su);

    if(su++ >= 6 - cnt) su = 0;
    // $('img').css('width',function(idx, val){
    $('img').width(function(idx, val){
        if(idx==su) return 200;
        return 0;
    })
    setTimeout(nextImg, 3000);
}
----------------------------------------------------
<script type="text/javascript">
    window.onload = function(){
        setInterval(loop, 3000);
    }
    function loop(){
        $('ul').children().first().appendTo('ul');
    }
</script>

width height

$('h1').width(300);
console.log($('h1').width(), $('h1').height());
$('li').css('background-color', 'gray').width(function(idx,val){
    return 100+50*idx;
});
console.log($('h1').innerWidth()) //padding을 포함한 길이
console.log($('h1').outerWidth(true)) //margin을 포함한 길이

$('h1').scrollTop(0); // 스크롤 위치 지정 0은 맨위로

클래스 관리 class

<style type="text/css" rel="stylesheet">
    ul>li{
        float: left;
        display: none;
    }
    .show{
        display: block;
    }
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
window.onload = function(){
    // 클래스
    $('li').first().addClass('show'); // 클래스 추가
    $('li').first().removeClass('show'); // 클래스 삭제
    $('li').first().hasClass('show'); // 클래스 있는지 확인
    $('li').first().toggleClass('show'); // 없으면 생김
    $('li').first().toggleClass('show'); // 있으면 없어짐
}
</script>

속성 attr

<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script ty="text/javascript">
    window.onload = function(){
        console.log($('input').eq(0).attr('type'));
        $('input').eq(0).attr('type', 'password');
        $('input').eq(0).attr('readonly', 'readonly');

        $(':radio').eq(1).attr('checked','checked');
        $(':checkbox').eq(1).attr('checked','checked');
        $('option').eq(1).attr('selected', 'selected');

        $('h1').attr('style','color:red');

        console.log($(':checkbox').eq(0).prop('checked')); // key값만 있는 속성들 확인
        console.log($('input').eq(2).prop('readonly'));

        $('input').eq(0).val('abcd');
        console.log($('input').eq(0).val());
    };
</script>

html & text

console.log($('ul').html());
console.log($('ul').text());
$('ul').html($('ul').html() + '<li>item5</li>'); // 누적
$('#target').html('<img src="imgs/thumnail1.jpg"/ width="100px">');
$('ol').html('<li>item9</li>'); // 덮어씌움
$('ol').append('<li>item10</li>'); // 추가
$('ol').prepend('<li>item11</li>'); // 맨앞 추가

element 옮기기

$('ol').prepend(document.querySelector('ul>li:last-child')); 
$('ol').prepend($('ul>li').last()); 
$('ul>li').last().prependTo('ol');
$('ol').children().last().appendTo('ul');

before after

$('ol').before('<p>before1</p>');
$('ol').before('<p>before2</p>');
$('ol').after('<p>after1</p>');
$('ol').after('<p>after2</p>');
$('ol').insertBefore('ul'); //ul의 앞으로 이동
$('ol').insertAfter('ul'); //ul의 뒤로 이동

요소 관리

// 요소 생성
// $('<h1>text</h1>').insertBefore('h1'); // 생성해서 넣기
// $('<h1/>').text('abcd').insertBefore('h1'); // 생성해서 넣기
// $(document.querySelector('h1')).text(); // 생성해서 넣기
$(['item1','item2','item3']).each(function(idx, ele){
    console.log(idx, ele);
});
$(function(){console.log('callback run...');});
// 요소 삭제
// $('h1').remove();
// $('h1').empty(); // 태그는 남음
// $('h1').detach(); // 재사용때
// 요소 복붙
$('h1').clone().insertBefore('ol');

wrap

<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    window.onload = function(){
        $('#li2').wrap('<ol>');
        $('.li1').wrapAll('#u1');
    }
</script>

end() 이전요소로가기 체이닝기법을 위함

<script src="js/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var cnt = 0;
    $(function(){
        // end() 이전요소로
        $('ul').children().first().clone().appendTo('ul')
                                  .end()
                          .end()
                          .next().clone().appendTo('ul');
        // $('ul').children().first().next().end(); // first()
        // setInterval(loop, 2000);
    });
    function loop(){
        cnt++
        if(cnt == 6) cnt = 0;
        $('ul').css('margin-left', (-100*cnt));
    }
</script>

'회고록(TIL&WIL)' 카테고리의 다른 글

TIL 2023.02.09 jQuery3 Servlet  (0) 2023.02.09
TIL 2023.02.08 jQuery 2  (0) 2023.02.08
TIL 2023.02.06 javascript 4  (0) 2023.02.06
TIL 2023.02.03 JavaScript 3  (0) 2023.02.03
TIL 2023.02.02 JavaScript 2  (0) 2023.02.02