FrontEnd/JavaScript

0916 JavaScript - jQuery, Ajax - DB연결

jeoniee 2022. 9. 16. 13:02
728x90
반응형

 

[ 목차 ] 

 

     


    <div></div>

    div는 division의 약자이다.

    분할하고 구분한다는 의미로, div 태그는 아무 의미가 없는 태그이지만 그 안에 내용이 있으면 그 내용이 박스 형태로 구분이 된다.

    즉, div 태그의 역할은 빈 박스, 하나의 구역을 생성해주는 것이다. 

     

     

     

    table 과 div 의 차이

    https://zinlee.tistory.com/entry/HTML-DIV%EC%99%80-TABLE%EC%9D%98-%EC%B0%A8%EC%9D%B4%EA%B0%80-%EB%AD%94%EA%B0%80%EC%9A%94

     

    HTML.. DIV와 TABLE의 차이가 뭔가요?

    어떤 분이 물었다. "HTML.. DIV와 TABLE의 차이가 뭔가요? 저는 그동안 table로 작업을 많이 해왓는데, div로 되어 있는 곳이 많더라구요. 차이가 먼가요?" 웹개발(frontend)을 시작한지 몇년 안된 분들에게

    zinlee.tistory.com

     

     

    아이디, 비밀번호 미 입력시 메시지 출력 

    $('#msg').html("아이디 입력").css('color','red');

    $('#msg').html("비밀번호 입력").css('color','red');

     

     

     

    jQuery의 효과

    show()       hide()     toggle()     slideDown()     slideUp()     slideToggle()
         fadeIn()     fadeOut()     fadeToggle()

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>jQuery/test9.html</title>
    <script type = "text/javascript" src = "jquery-3.6.1.js"></script>
    <script type = "text/javascript">
    	$(document).ready(function(){
    		//효과 show() hide() toggle() slideDown() slideUp() slideToggle()
    		//     fadeIn() fadeOut() fadeToggle()
    		//h1태그를 클릭 했을 때 
    		$('h1').click(function(){
    		//	alert("클릭");
    			$(this).next().toggle('slow',function(){
    		//this 는 클릭한 대상. next 는 다음 대상 태그 
    				alert('효과 끝');
    				
    			});
    
    			
    		});
    		
    	});
    
    
    </script>
    </head>
    <body>
    <h1>열고 닫기1</h1>
    <div>
    <h1>제목1</h1>
    <p>내용1</p>
    </div>
    </body>
    </html>

     

    애니메이션 효과 

    	$('#d').click(function(){
    		//alert("클릭");
    		var w= $(this).css('width');
    		var h= $(this).css('height');
    //		alert(w);
    //		alert(h);
    //		animation() 함수를 이용해 클릭 시 너비 높이 50씩 증가
    		$(this).animate({
    			width  : parseInt(w)+50,
    			height : parseInt(h)+50
    		});
    	});
    	
    });

    body 밑에 div 태그 입력

    <div id="d"></div>


    script 타입 입력

    <style type="text/css">
    #d
    {
    width: 50px; height: 50px; background-color: orange;
    }
    </style>

     

     

     

     

     

    AJAX


    Ajax란 Asynchronous JavaScript and XML의 약자입니다.

    Ajax는 빠르게 동작하는 동적인 웹 페이지를 만들기 위한 개발 기법의 하나입니다.

     

    Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있습니다.

    즉 Ajax를 이용하면 백그라운드 영역에서 서버와 통신하여, 그 결과를 웹 페이지의 일부분에만 표시할 수 있습니다.

     

    이때 서버와는 다음과 같은 다양한 형태의 데이터를 주고받을 수 있습니다.

     

     - JSON

     - XML

     - HTML

     - 텍스트 파일 등


    Ajax의 장점

    Ajax를 이용하면 다음과 같은 장점이 있습니다.

    • 페이지 새로고침 없이 서버에 요청
    • 서버로부터 데이터를 받고 작업을 수행

     

    1. 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있습니다.

    2. 웹 페이지가 로드된 후에 서버로 데이터 요청을 보낼 수 있습니다.

    3. 웹 페이지가 로드된 후에 서버로부터 데이터를 받을 수 있습니다.

    4. 백그라운드 영역에서 서버로 데이터를 보낼 수 있습니다.


    Ajax의 한계

    Ajax를 이용하면 여러 장점을 가지지만, Ajax로도 다음과 같은 일들은 처리할 수 없습니다.

     

    1. Ajax는 클라이언트가 서버에 데이터를 요청하는 클라이언트 풀링 방식을 사용하므로, 서버 푸시 방식의 실시간 서비스는 만들 수 없습니다.

    2. Ajax로는 바이너리 데이터를 보내거나 받을 수 없습니다.

    3. Ajax 스크립트가 포함된 서버가 아닌 다른 서버로 Ajax 요청을 보낼 수는 없습니다.

    4. 클라이언트의 PC로 Ajax 요청을 보낼 수는 없습니다.

     

     

     

    html.jsp, html.html 생성 

     

     

    html.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <% 
    //<h1>jQuery2/html1.jsp</h1>
    %>

    출력 결과만 나오게 해야해서 이외의 양식들은 다 지워준다. 

     

    html.html
    <script type = "text/javascript" src="../jQuery/jquery-3.6.1.js"></script>
    <script type = "text/javascript">
    $(document).ready(function(){
    	alert("클릭");
    	$.ajax({
    		url:'html1.jsp',
    		success:function(rdata){
    			//html1.jsp 에서 출력한 결과를 성공적으로 rdata 변수에 받아옴
    			//body태그 뒤부분에 출력 
    			$('body').append(rdata); //return data를 body태그 뒤에 출력하겠다. 
    			
    		}
    		
    	});

     

    문제


    click() 버튼을 클릭했을 때, 
    ajax() html1.jsp에서 출력한 결과를 성공적으로 rdata변수에 받아옴 (append() table 태그 뒤부분에 출력)
    $('#btn').click(function(){
    	//alert("클릭");
    	
    	$.ajax({
    		url:'html1.jsp',
    		success:function(rdata){
    			$('table').append('<tr><td>'+ rdata + '</td></tr>');
    			}
    		});
    	});
    	
    	
    });
    
    </script>
    </head>
    <body>
    <input type="button" value = "버튼" id="btn">
    <table border = "1">
    <tr>
    	<td>내용</td>
    	<td></td>
    </tr>
    </table>

     

     

    html2.html
    <title>jQuery2/html2.html</title>
    <script type = "text/javascript" src="../jQuery/jquery-3.6.1.js"></script>
    <script type ="text/javascript">
    	$(document).ready(function(){
    		$('#btn').click(function(){
    			alert($('#id').val());
    			
    		//alert($('#id').val());
    		$.ajax({
    			url:'html2.jsp',
    			data:{'id':$('#id').val()},
    			success:function(rdata){
    				$('#idcheck').html(rdata);
    				
    			}
    			});
    		});
    		
    	});
    	
    </script>
    </head>
    <body>
    아이디 : <input type= "text" name = "id" id ="id">
    <input type = "button" value ="아이디 중복체크" id="btn">
    <div id = "idcheck"></div>

    아무것도 지정 안했으니 get 방식이다. 

     

    html2.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
     <%
     //<h1>jQuery2/html2.jsp</h1>
     
     String id = request.getParameter("id");
     
     
     %>
     <%=id+"아이디중복"%>

     

     

    db 연결 

    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.sql.PreparedStatement"%>
    <%@page import="java.sql.DriverManager"%>
    <%@page import="java.sql.Connection"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
     <%
     //<h1>jQuery2/html2.jsp</h1>
     
     String id = request.getParameter("id");
     String result = "";
    //  if(id.equals("kim")){
    // 	 result = "아이디 중복";
    //  }else{
    // 	 result = "아이디 사용가능"; 
    //  }
    
    // 디비 연결 정보 (상수)
    	final String DRIVER = "com.mysql.cj.jdbc.Driver";
    	final String DBURL = "jdbc:mysql://localhost:3306/jspdb";
    	final String DBID = "root";
    	final String DBPW = "1234";
    	
    	// 1.드라이버 로드 
    	
    	   Class.forName(DRIVER);
    		System.out.println(" 드라이버 로드 성공! ");
    		
    	// 2. 디비 연결 
    	Connection con = DriverManager.getConnection(DBURL, DBID, DBPW);
    	System.out.println(" 디비 연결 성공! ");
    	System.out.println("con : " + con);
    	
    	// 3. SQL 작성 & PSTMT 
    	// itwill_member 테이블에 있는 남자(M)의 정보만 출력
    	// ? 의미는, 타입 상관없이 값을 받겠다는 말이라서, ''을 넣을 필요가 없다. 
    	String sql = "select * from itwill_member where id=?";
    	
    	PreparedStatement pstmt = con.prepareStatement(sql);
    	
    	// ???
    	pstmt.setString(1,id);
    	
    	// 4. SQL 실행 
    	// pstmt.executeUpdate() : insert구문
    	// pstmt.executeQuery() : select 구문
    	ResultSet rs = pstmt.executeQuery();
    	System.out.println(" SQL 실행 완료! ");
    	
    	// 5. 데이터 처리 
    	// 정보를 가져다가 출력 
    
    	// rs.next() : 레코드셋의 커서를 움직여서 데이터가 있는지 없는지 체크 
    	
    		if(rs.next()){
    			//아이디 있음, 아이디 중복 
    			result="아이디 중복";
    			
    		}else{
    			//아이디 없음, 아이디 사용 가능 
    			result="아이디 사용가능";
    			
    		}
    	
    	
     
     %>
     <%=id+":" +result%>
    728x90
    반응형