ddit/Python

220907파이썬, DJango에서 ajax 사용해보기

ssong2ku 2022. 9. 13. 08:25
728x90

.js = static 파일

html = 자바에서 static 장고에서는 dynamic

staticmethod 장점

  • self 인자를 사용할 필요가 없다.
  • 인스턴스화할 때 static method에 대해서는 bound-method를 생성해줄 필요가 없어 메모리 사용량을 줄일 수 있다.
  • 인스턴스 오브젝트 자체에 의존하지 않는다는 것을 의미하여 코드의 가시성이 좋아진다.

https://myjamong.tistory.com/289

 

Python staticmethod 왜 사용해야할까?

Python staticmethod Python staticmethod는 @staticmethod 데코레이터를 사용한 정적 메소드 입니다. 인스턴스 메소드와는 다르게 self 인자를 받지 않는다. 클래스 이름으로 직접 메소드를 호출할 수 있다. 인

myjamong.tistory.com

 

파이썬에서 제이쿼리 사용 시

프로젝트 아래에 static 프로젝트 만들어주고 제이쿼리 파일 넣어주기

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Insert title here</title>
<script src="static/jquery-3.6.0.min.js"></script>
<script type="text/javascript">

AJAX사용

-view

from django.shortcuts import render
from django.http.response import JsonResponse
from SPA_EMP.daoemp import DaoEmp


de=DaoEmp()

def emp(request):
    return render(request,"emp.html")

def emp_list_ajax(request):
    mylist=de.mylist()
    
    context={
        'mylist':mylist
    }
    return JsonResponse(context)

-urls

"""SPA_EMP URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/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 SPA_EMP import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.emp),
    path('emp_list.ajax', views.emp_list_ajax),
]

-HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Insert title here</title>
<script src="static/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
   function myclick() {
      $.ajax({
         type: "GET", //요청 메소드 방식
         url:"emp_list.ajax",
         dataType:"json", //서버가 요청 URL을 통해서 응답하는 내용의 타입
         success : function(data){
            var list=data.mylist;
            console.log(data.list)
           	var txt ="";
            for(var i =0; i<list.length; i++){
            	var e_id=list[i].e_id;
            	var e_name=list[i].e_name;
            	var sex=list[i].sex;
            	var addr=list[i].addr;
            	txt+=`
	    			<tr>
	    				<td>${e_id}</td>
	    				<td>${e_name}</td>
	    				<td>${sex}</td>
	    				<td>${addr}</td>
	    			</tr>
    			`;	
            }
            if(list.length==0){
            	txt+=`
        			<tr>
        				<td colspan='4'>해당하는 데이터가 없습니다.</td>
        			</tr>
        		`;	
            	
            }
            $("#mytbody").html(txt);
         },
        
      });

   }
</script>

</head>
<body>
<table border="1">
	<thead>
		<tr>
			<td>사번</td>
			<td>이름</td>
			<td>성별</td>
			<td>주소</td>
		</tr>
	</thead>
	<tbody id=mytbody>
	
	
	</tbody>
</table>
 
   <a href="javascript:myclick()">click</a>
</body>
</html>
728x90