Python Django

Python Django 18 - Python Ajax

코딩탕탕 2022. 10. 23. 15:43

 

urls.py

from django.contrib import admin
from django.urls import path
from myapp import views 

urlpatterns = [
    path("admin/", admin.site.urls),
    
    path("", views.indexFunc),
    path("startajax", views.Func1),
    path("goajax", views.Func2),
]

 

views.py

from django.shortcuts import render
import time
import json
from django.http.response import HttpResponse

# Create your views here.

lan = {
    'id' : 123,
    'name' : '파이썬',
    'history' : [
        {'date':'2022-9-20', 'exam' : 'basic'},
        {'date':'2022-10-20', 'exam' : 'django'},
    ]
}
 
def testFunc():
    print(type(lan)) # <class 'dict'>
    
    # JSON 인코딩 : Python Object(dict, list, tuple...)를 JSON 문자열로 변경
    JSONString = json.dumps(lan, indent=4)
    print(JSONString)
    print(type(JSONString)) # <class 'str'>
    # 모양을 유지한 상태에서 타입만 str 타입으로 바꾼 것이다.
    
    # JSON 디코딩 : JSON 문자열을 Python Object(dict, list, tuple...)로 변경
    dic = json.loads(JSONString)
    print(type(dic)) # <class 'dict'>
    print(dic)
    print(dic['name'])


def indexFunc(request):
    testFunc()
    return render(request, 'abc.html')


def Func1(request):
    msg = request.GET.get('msg')
    msg = "nice " + msg
    print(msg)
    context = {'key':msg}
    time.sleep(5)
    return HttpResponse(json.dumps(context), content_type="application/json")
    # dict 타입을 그냥 넘기면 안 되고 문자열로 바꿔서 넘겨주어야 된다. json 보낼 시
    

def Func2(request):
    datas = [
        {'irum':'홍길동','nai':22},
        {'irum':'고길동','nai':32},
        {'irum':'신길동','nai':42}
    ]
    
    return HttpResponse(json.dumps(datas), content_type="application/json")
    # dict 타입을 그냥 넘기면 안 되고 문자열로 바꿔서 넘겨주어야 된다. json 보낼 시

<console>
<class 'dict'>
{
    "id": 123,
    "name": "\ud30c\uc774\uc36c",
    "history": [
        {
            "date": "2022-9-20",
            "exam": "basic"
        },
        {
            "date": "2022-10-20",
            "exam": "django"
        }
    ]
}
<class 'str'>
<class 'dict'>
{'id': 123, 'name': '파이썬', 'history': [{'date': '2022-9-20', 'exam': 'basic'}, {'date': '2022-10-20', 'exam': 'django'}]}
파이썬

JOSN은 dict 타입이랑 매우 잘 맞는다. json을 import 한다.

json.dumps() 함수로 dict 타입을 str 타입으로 바꿀 수 있다.

반대로 json.loads()함수로 문자열로 변했던 것을 다시 dict 타입으로 변환 시킬 수 있다.

dict 타입으로 변환시키면 key값으로 벨류값을 호출할 수 있다.

리턴 시에는 return HttpResponse(json.dumps(context), content_type="application/json")

HttpResponse를 import하고 인코딩 한 상태로 리턴시킨다. html페이지에서 그것을 가져오는 것이다.(디코딩)

 

 

abc.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
let xhr;

window.onload = function(){
	document.querySelector("#btn1").addEventListener("click", function(){
		// alert('a');
		// XmlHttpRequest 객체로 웹서버와 통신
		xhr = new XMLHttpRequest()
		// console.log(xhr);
		
		xhr.onreadystatechange = function(){
			//alert(xhr.readyState); // 0 ~ 4의 값을 갖는다.
			if(xhr.readyState === XMLHttpRequest.DONE){
				// alert(xhr.status);
				if(xhr.status === 200){ // 200이라는 숫자는 정상작동이라는 의미이다.
					// console.log(xhr.response);
					process1();
				}
			}
		}
		
		url = "startajax?msg=" + document.querySelector("#txtMsg").value;
		xhr.open("GET", url, true);
		xhr.send();
	});
	
	document.querySelector("#btn2").onclick = function(){
		xhr = new XMLHttpRequest()
		xhr.onreadystatechange = function(){
			if(xhr.readyState === XMLHttpRequest.DONE){
				// alert(xhr.status);
				if(xhr.status === 200){
					// console.log(xhr.response);
					process2();
				}
			}
		}
		xhr.open("GET", "goajax", true);
		xhr.send();
	}
}

function process1(){
	// alert(xhr.responseText);
	let parseData = JSON.parse(xhr.responseText);
	document.querySelector("#showData1").innerText = xhr.responseText;
}

function process2(){
	// alert(xhr.responseText);
	let parseData2 = JSON.parse(xhr.responseText);
	let str = "";
	for(let i=0; i<parseData2.length; i++){
		str += parseData2[i].irum + " " + parseData2[i].nai + "<br>";
	}
	document.querySelector("#showData2").innerHTML = str;
	
}
</script>
</head>
<body>
<p>Ajax 연습</p>
<textarea rows="5" cols="50"></textarea>
<br />
자료 입력 : <input type="text" id="txtMsg" value="korea"/>
<button id="btn1">Ajax test1</button>
<br />
<div id="showData1"></div>
<hr>
<button id="btn2">Ajax test2</button>
<div id="showData2"></div>
</body>
</html>

자바스크립트에 집중해야된다. 자바스크립트에서 views.py로부터 받은 데이터를 디코딩해서 출력하는 것이다. XmlHttpRequest객체를 생성해서 정상적으로 데이터가 도달하면 process1()함수를 호출하는 것으로 데이터가 출력된다.

XmlHttpRequest객체는 정보가 잘 도착하는지 확인하는 객체하고 생각하면 편하다.

parse 메소드는 string 객체를 json 객체로 변환시켜준다. 이렇게 하는 이유는 views.py에서 값을 인코딩 하여 string 값으로 보내주었기 때문에 받을 때, 다시 json 타입으로 바꿔주어야 하기때문이다.(디코딩)