관리 메뉴

거니의 velog

231113_Django 개론 4 본문

대덕인재개발원/대덕인재개발원_파이썬 프로그래밍

231113_Django 개론 4

Unlimited00 2023. 11. 13. 08:30

[js06.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS06</title>
		<script type="text/javascript">
			function myclick(obj){
				var obj_it = document.getElementById("it");
				
				var str_new = obj.innerHTML;
				var str_old = obj_it.value;
				
				obj_it.value = str_old + str_new;
			}
			function myCall(){
				var obj_it = document.getElementById("it");
				var str_tel = obj_it.value;
				alert("CALLING ~ \n" + str_tel);
			}
		</script>
		<style>
			table {
				text-align: center;
			}
			table button {
				width: 100%;
			}
			input {
				text-align: right;
			}
		</style>
	</head>
	<body>
		JS06
		<table border="1">
			<tr>
				<td colspan="3">
					<input type="text" id="it" />
				</td>
			</tr>
			<tr>
				<td><button type="button" class="btn" onclick="myclick(this)">1</button></td>
				<td><button type="button" class="btn" onclick="myclick(this)">2</button></td>
				<td><button type="button" class="btn" onclick="myclick(this)">3</button></td>
			</tr>
			</tr>
			<tr>
				<td><button type="button" class="btn" onclick="myclick(this)">4</button></td>
				<td><button type="button" class="btn" onclick="myclick(this)">5</button></td>
				<td><button type="button" class="btn" onclick="myclick(this)">6</button></td>
			</tr>
			<tr>
				<td><button type="button" class="btn" onclick="myclick(this)">7</button></td>
				<td><button type="button" class="btn" onclick="myclick(this)">8</button></td>
				<td><button type="button" class="btn" onclick="myclick(this)">9</button></td>
			</tr>
			<tr>
				<td>
					<button type="button" class="btn" onclick="myclick(this)">0</button>
				</td>
				<td colspan="2">
					<button type="button" class="btn_call" onclick="myCall()">CALL</button>
				</td>
			</tr>
		</table>
	</body>
</html>

- http://127.0.0.1:8000/static/js06.html


* jQuery로 바꾸기

[jq01.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS01</title>
		<script src="jquery-3.7.1.js"></script>
		<script>
			$(function(){
				$("#btn").bind("click", function(){
					$("#mydiv").html("Good Evening");
				});
			});
		</script>
	</head>
	<body>
		JS01
		<div id="mydiv">Good Morning</div>
		<button type="button" id="btn">click</button>
	</body>
</html>

- http://127.0.0.1:8000/static/jq01.html


[jq02.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS02</title>
		<script src="jquery-3.7.1.js"></script>
		<script>
		$(function(){
			$("#btn").bind("click", function(){
				var ita = $("input[name=ita]").val();
				var itb = $("input[name=itb]").val();
				var a = parseInt(ita);
				var b = parseInt(itb);
				var sum = a + b;
				$("input[name=itc]").val(sum);
			});
		});
		</script>
	</head>
	<body>
		JS02
		<br />
		<input type="text" name="ita" /> 
		+ 
		<input type="text" name="itb" />
		<button type="button" id="btn">=</button>
		<input type="text" name="itc" readonly />
	</body>
</html>

- http://127.0.0.1:8000/static/jq02.html


[jq03.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS03</title>
		<script src="jquery-3.7.1.js"></script>
		<script>
		$(function(){
			function myclick(){
				var obj_select = $(".mysel").val();
				var obj_ta = $("#myta");
				
				var gugudan_txt = "";
				
				for(var i = 1; i <= 9; i++) {
					gugudan_txt += obj_select + "*" + i + "=" + (obj_select * i) + "\n";
				}
				
				obj_ta.val(gugudan_txt);
			}
			$("#btn").click(function(){
				myclick();
			});
			$(".mysel").change(function(){
				myclick();
			});
		});
		</script>
	</head>
	<body>
		JS03
		<table border="1">
			<tr>
				<td>출력단수</td>
				<td>
					<select class="mysel">
						<option value="2">2단</option>
						<option value="3">3단</option>
						<option value="4">4단</option>
						<option value="5">5단</option>
						<option value="6">6단</option>
						<option value="7">7단</option>
						<option value="8">8단</option>
						<option value="9">9단</option>
					</select>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<button type="button" id="btn">출력하기</button>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<textarea id="myta" rows="10" cols="10"></textarea>
				</td>
			</tr>
		</table>
	</body>
</html>

- http://127.0.0.1:8000/static/jq03.html


[jq04.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS04</title>
		<script src="jquery-3.7.1.js"></script>
		<script>
		$(function(){
			function getStar(cnt){
				ret = "";
				for(var i = 0; i < cnt; i++) {
					ret += "★";
				}
				return ret;
			}
			$("#btn").click(function(){
				var it_first = $("#it_first").val();
				var it_last = $("#it_last").val();
				var mydiv = $("#mydiv");
				
				var int_it_first = parseInt(it_first);
				var int_it_last = parseInt(it_last);
				
				var star_txt = "";
				for(var i = int_it_first; i <= int_it_last; i++) {
					star_txt += getStar(i) + "<br />";
				}
				mydiv.html(star_txt);
			});
		});
		</script>
		<style type="text/css">
			input[type=text] {
				width: 50px;
			}
			table {
				width: 300px;
			}
			#mydiv {
				height: 500px;
			}
		</style>
	</head>
	<body>
		JS04
		<table border="1">
			<colgroup>
				<col width="30%" />
				<col width="70%" />
			</colgroup>
			<tr>
				<td>시작별수 : </td>
				<td>
					<input type="text" id="it_first" />
				</td>
			</tr>
			<tr>
				<td>끝별수 : </td>
				<td>
					<input type="text" id="it_last" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="button" value="출력하기" id="btn" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<div id="mydiv"></div>
				</td>
			</tr>
		</table>
	</body>
</html>

- http://127.0.0.1:8000/static/jq04.html


[jq05.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS05</title>
		<script src="jquery-3.7.1.js"></script>
		<script>
		$(function(){
			$("#btn").click(function(){
				var arr = new Array();
				for(var i = 1; i <= 45; i++) {
					arr.push(i);
				}
				for(var i = 0; i < 1000; i++) {
					var rnd = parseInt(Math.random() * 45);
					var temp = arr[0];
					arr[0] = arr[rnd];
					arr[rnd] = temp;
				}
				for(var i = 0; i < 6; i++) {
					for(var j = 0; j < 6; j++) {
						if(arr[i] < arr[j]) {
							var a = arr[i]
				            var b = arr[j]
				            arr[i] = b
				            arr[j] = a
						}
					}
				}
				$(".myspan").each(function(i, v){
					$(this).html(arr[i]);
				});
			});
		});
		</script>
	</head>
	<body>
		JS05
		<table border="1">
			<tr>
				<td><span class="myspan">__</span></td>
				<td><span class="myspan">__</span></td>
				<td><span class="myspan">__</span></td>
				<td><span class="myspan">__</span></td>
				<td><span class="myspan">__</span></td>
				<td><span class="myspan">__</span></td>
			</tr>
			<tr>
				<td colspan="6">
					<button type="button" id="btn">CLICK</button>
				</td>
			</tr>
		</table>
	</body>
</html>

- http://127.0.0.1:8000/static/jq05.html


[jq06.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>JS06</title>
		<script src="jquery-3.7.1.js"></script>
		<script>
		$(function(){
			
			function myclick(obj){
				var str_new = $(obj).text();
				var str_old = $("#it").val();
				
				$("#it").val(str_old + str_new);
			}
			$(".btn").click(function(e){
				console.log(this);
				console.log(e.target);
				myclick(e.target);
				/* var thisIs = $(this);
				var str_new = thisIs.text();
				var str_old = $("#it").val();
				
				$("#it").val(str_old + str_new); */
			});
			$(".btn_call").click(function(){
				var str_tel = $("#it").val();
				alert("CALLING ~ \n" + str_tel);
			});
			
		});
		</script>
		<style>
			table {
				text-align: center;
			}
			table button {
				width: 100%;
			}
			input {
				text-align: right;
			}
		</style>
	</head>
	<body>
		JS06
		<table border="1">
			<tr>
				<td colspan="3">
					<input type="text" id="it" />
				</td>
			</tr>
			<tr>
				<td><button type="button" class="btn">1</button></td>
				<td><button type="button" class="btn">2</button></td>
				<td><button type="button" class="btn">3</button></td>
			</tr>
			</tr>
			<tr>
				<td><button type="button" class="btn">4</button></td>
				<td><button type="button" class="btn">5</button></td>
				<td><button type="button" class="btn">6</button></td>
			</tr>
			<tr>
				<td><button type="button" class="btn">7</button></td>
				<td><button type="button" class="btn">8</button></td>
				<td><button type="button" class="btn">9</button></td>
			</tr>
			<tr>
				<td>
					<button type="button" class="btn">0</button>
				</td>
				<td colspan="2">
					<button type="button" class="btn_call">CALL</button>
				</td>
			</tr>
		</table>
	</body>
</html>

- http://127.0.0.1:8000/static/jq06.html


[HELLO_AJAX.settings]

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'HELLO_AJAX',
]

[ajax.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>AJAX HTML</title>
		<script src="jquery-3.7.1.js"></script>
	</head>
	<body>
		AJAX HTML
	</body>
</html>

- http://127.0.0.1:8000/static/ajax.html


https://codong.tistory.com/29

 

[django] ajax를 이용해서 데이터 주고받기

😆 개요 django로 웹 서비스를 만들어 보면서 비동기 방식을 안 써볼 수가 없다. 그!래!서! 비동기 통신 방식으로 많이 이용하고 있는 jquery의 ajax의 정말 기초적이 사용방법을 알아보려고 한다. 혹

codong.tistory.com

[HELLO_AJAX.views]

import pymysql # PyMySQL-1.1.0
from django.http.response import JsonResponse
from flask import json
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def ajax(request):
    if request.method == 'POST':
        dict = json.loads(request.body)
        # print(dict)
        print(dict['e_id'])
        context = {
            'result': dict,
        }
        return JsonResponse(context)

[HELLO_AJAX.urls]

"""
URL configuration for HELLO_AJAX project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from HELLO_AJAX import views

urlpatterns = [
    path('ajax', views.ajax),
]

[ajax.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>AJAX HTML</title>
		<script src="jquery-3.7.1.js"></script>
		<script type="text/javascript">
			function fn_ajax(){
				var data = {
					'e_id' : 1
				};
			    $.ajax({
			        type : 'POST',
			        url : '/ajax',
			        data : JSON.stringify(data),
			        success : function(res){
			            console.log(res);
			        }
			   });
			}
		</script>
	</head>
	<body>
		AJAX HTML<br />
		<a href="javascript:fn_ajax()">AJAX</a>
	</body>
</html>


[HELLO_AJAX.daoEmp]

import pymysql # PyMySQL-1.1.0

class DaoEmp:
    def __init__(self):
        print("생성자")
        self.conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    
    def selectList(self):
        sql = "select * from emp"
        self.cur.execute(sql)
        
        lists = self.cur.fetchall()
        return lists
    
    def selectOne(self, e_id):
        sql = f"""
            select * from emp 
            where e_id = '{e_id}'
        """
        self.cur.execute(sql)
        
        vo = self.cur.fetchone()
        return vo
    
    def insert(self, e_id, e_name, gen, addr):
        sql = f"""
            INSERT INTO emp (e_id, e_name, gen, addr) 
                 VALUES ('{e_id}', '{e_name}', '{gen}', '{addr}')
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def update(self, e_id, e_name, gen, addr):
        sql = f"""
            UPDATE emp SET 
                e_name = '{e_name}'
                , gen = '{gen}'
                , addr = '{addr}'
                WHERE e_id = '{e_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def delete(self, e_id):
        sql = f"""
            DELETE FROM emp 
            WHERE e_id = '{e_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
        
    # 소멸자 : destroyer
    def __del__(self):
        print("소멸자")
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    de = DaoEmp()
    
    list = de.selectList()
    print(list)
    
    # vo = de.selectOne('10')
    # print(vo)
    
    # cnt = de.insert('10', '10', '1', '10')
    # print(cnt)
    
    # cnt = de.update('10', '123', '1', '123')
    # print(cnt)
    
    # cnt = de.delete('10')
    # print(cnt)
from django.http.response import JsonResponse
from flask import json
from django.views.decorators.csrf import csrf_exempt
from HELLO_AJAX.daoEmp import DaoEmp

@csrf_exempt
def ajax(request):
    dict = json.loads(request.body)
    # print(dict)
    print(dict['e_id'])
    context = {
        'result': dict,
    }
    return JsonResponse(context)

@csrf_exempt
def ajax_selectlist(request):
    
    de = DaoEmp();
    list = de.selectList()
    
    context = {
        'list': list,
    }
    
    return JsonResponse(context)
"""
URL configuration for HELLO_AJAX project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from HELLO_AJAX import views

urlpatterns = [
    path('ajax', views.ajax),
    path('selectlist.ajax', views.ajax_selectlist),
]

[emp.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>EMP_HTML</title>
		<script src="jquery-3.7.1.js"></script>
		<script type="text/javascript">
			function fn_list(){
				var param = {
					'e_id' : 1
				};
			    $.ajax({
			        type : 'POST',
			        url : '/selectlist.ajax',
			        data : JSON.stringify(param),
			        success : function(res){
			            console.log(res.list);
			            var list = res.list;
			            var txt = "";
			            for(var i=0; i < list.length; i++) {
			            	var vo = list[i];
			            	var e_id = vo.e_id;
			            	var e_name = vo.e_name;
			            	var gen = vo.gen;
			            	var addr = vo.addr;
			            	txt += `
			            		<tr>
									<th>${e_id}</th>
									<th>${e_name}</th>
									<th>${gen}</th>
									<th>${addr}</th>
								</tr>
			            	`;
			            }
			            //console.log(txt);
			            $("#mytbody").html(txt);
			        }
			   });
			}
			$(function(){
				fn_list();
			});
		</script>
	</head>
	<body>
		EMP_HTML
		<table border="1">
			<thead>
				<tr>
					<th>사원번호</th>
					<th>이름</th>
					<th>성별</th>
					<th>주소</th>
				</tr>
			</thead>
			<tbody id="mytbody">
				<tr>
					<td colspan="4">검색된 데이터가 없습니다</td>
				</tr>
			</tbody>
		</table>
	</body>
</html>

- http://127.0.0.1:8000/static/emp.html


from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from HELLO_AJAX.daoEmp import DaoEmp
import json

@csrf_exempt
def ajax(request):
    context = {
        'result': dict,
    }
    return JsonResponse(context)

@csrf_exempt
def ajax_selectlist(request):
    de = DaoEmp();
    list = de.selectList()
    
    context = {
        'list': list,
    }
    
    return JsonResponse(context)

@csrf_exempt
def ajax_select(request):
    dict = json.loads(request.body)
    e_id = dict['e_id']
    print(e_id)
    
    de = DaoEmp();
    list = de.selectOne(e_id);
    
    context = {
        'list': list,
    }
    
    return JsonResponse(context)
"""
URL configuration for HELLO_AJAX project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from HELLO_AJAX import views

urlpatterns = [
    path('ajax', views.ajax),
    path('selectlist.ajax', views.ajax_selectlist),
    path('select.ajax', views.ajax_select),
]
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>EMP_HTML</title>
		<script src="jquery-3.7.1.js"></script>
		<script type="text/javascript">
		
			function fn_selectlist(){
				var param = {};
			    $.ajax({
			        type : 'POST',
			        url : '/selectlist.ajax',
			        data : JSON.stringify(param),
			        success : function(res){
			            console.log(res.list);
			            var list = res.list;
			            var txt = "";
			            for(var i=0; i < list.length; i++) {
			            	var vo = list[i];
			            	var e_id = vo.e_id;
			            	var e_name = vo.e_name;
			            	var gen = vo.gen;
			            	var addr = vo.addr;
			            	txt += `
			            		<tr>
									<th><a href='javascript:fn_select("${e_id}")'>${e_id}</a></th>
									<th>${e_name}</th>
									<th>${gen}</th>
									<th>${addr}</th>
								</tr>
			            	`;
			            }
			            //console.log(txt);
			            $("#mytbody").html(txt);
			        }
			   });
			}
			
			function fn_select(e_id){
				console.log(e_id);
				var param = {
					'e_id' : e_id
				};
			    $.ajax({
			        type : 'POST',
			        url : '/select.ajax',
			        data : JSON.stringify(param),
			        success : function(res){
			            console.log(res);
			            console.log(res.list);
			            var list = res.list;
			            $("#e_id").val(list.e_id);
			            $("#e_name").val(list.e_name);
			            $("#gen").val(list.gen);
			            $("#addr").val(list.addr);
			        }
			   });
			}
			
			$(function(){
				fn_selectlist();
				fn_select();
			});
			
		</script>
	</head>
	<body>
		EMP_HTML
		<table border="1">
			<colgroup>
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
			</colgroup>
			<thead>
				<tr>
					<th>사원번호</th>
					<th>이름</th>
					<th>성별</th>
					<th>주소</th>
				</tr>
			</thead>
			<tbody id="mytbody">
				<tr>
					<td colspan="4">검색된 데이터가 없습니다</td>
				</tr>
			</tbody>
		</table>
		<br />
		<hr />
		<br />
		<table border="1">
			<colgroup>
				<col width="30%" />
				<col width="70%" />
			</colgroup>
			<tr>
				<td>사번</td>
				<td>
					<input type="text" id="e_id" name="e_id" />
				</td>
			</tr>
			<tr>
				<td>이름</td>
				<td>
					<input type="text" id="e_name" name="e_name" />
				</td>
			</tr>
			<tr>
				<td>성별</td>
				<td>
					<input type="text" id="gen" name="gen" />
				</td>
			</tr>
			<tr>
				<td>주소</td>
				<td>
					<input type="text" id="addr" name="addr" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<button type="button">추가</button>
					<button type="button">수정</button>
					<button type="button">삭제</button>
				</td>
			</tr>
		</table>
	</body>
</html>

'대덕인재개발원 > 대덕인재개발원_파이썬 프로그래밍' 카테고리의 다른 글

231115_Node.js 개론 1  (0) 2023.11.15
231114_Django 개론 5  (0) 2023.11.14
231110_Django 개론 3  (0) 2023.11.10
231109_Django 과제 1  (0) 2023.11.09
231109_Django 개론 2  (0) 2023.11.09