1. 인코딩(encoding)
(1) 웹에서는 문자열로 데이터를 받기 때문에 인코딩이 필요함
(2) python object(Dict, List, Tuple...)를 문자열로 변경하는 작업
(3) 형식: json.dumps(json type으로 변경할 object, indent=들여쓰기 할 칸 수)
2. 디코딩(decoding)
(1) 웹에서 문자열로 넘어오는 데이터를 python의 object로 변경하는 작업
(2) 형식: json.loads(json)
3. views.py에서 json형으로 데이터를 넘겨줄 때 HttpResponse(data, content_type) 사용
(1) 형식: return HttpResponse(data, content_type)
(2) response를 반환하는 가장 기본적인 함수
(3) Json이나 html을 반환
(4) 제어권을 자바스크립트로 다시 넘긴 것
ex) return HttpResponse(json.dumps(context), content_type = 'application/json')
è context데이터를 json으로 바꿔서 넘겨주는 것
è json.dumps(context)를 json형으로 보낸다는 것
è xml 파일을 넘길 때는 content_type = 'application/xml'
4. JQuery에서 Ajax 함수
(1) 형식: $.ajax({속성});
(2) 속성
1) url: 통신을 원하고자 하는 URL주소를 입력(필수 입력 값)
2) type: GET, POST등의 통신 방식 지정
3) data: 서버로 보낼 데이터를 입력
4) dataType: 통신의 결과로 넘어올 데이터의 종류를 지정
5) success(data)
① 통신 성공 시 호출해야 하는 함수를 지정
② 매개변수로 결과로 넘어온 데이터를 받음
6) error: 통신 실패 시 호출해야 하는 함수를 지정
<예시>
1. urls.py
from django.contrib import admin
from django.urls import path
from myajaxapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.indexFunc),
path('startajax', views.func1),
path('goajax', views.func2)
]
2. views.py
from django.shortcuts import render
import json
from django.http.response import HttpResponse
import time
lan = {
'id':111,
'name':'파이썬',
'history':[
{'date':'2021-2-12', 'exam':'basic'},
{'date':'2021-2-22', 'exam':'django'}
]
}
def test(): # json의 encoding, decoding연습
print(type(lan)) #<class 'dict'>
# json encoding : python object(Dict, List, Tuple...)를 문자열로 변경하는 작업
#json.dumps()
#웹에서는 문자열로 주고받기 때문에 인코딩이 필요함
jsonstring = json.dumps(lan, indent=4) #4칸 들여쓰기-> 메모리낭비
print(jsonstring)
print(type(jsonstring))
print('-------------'*10)
# json decoding : 문자열을 python object(Dict, List, Tuple...)로 변경하는 작업
#json.loads()
dic = json.loads(jsonstring)
print(dic)
print(type(dic))
print(dic['name'])
for h in dic['history']:
print(h['date'], h['exam'])
def indexFunc(request):
#test()
return render(request, 'abc.html')
def func1(request):
msg = request.GET['msg'] #받아오기
print(msg)
time.sleep(5)#5초의 지연시간 준 것
context = {'key':msg + 'ajax 요청처리'} #넘겨주기 key-value형식으로
#return render(request, 'abc.html') 이걸로 넘기면 ajax처리 안됨
return HttpResponse(json.dumps(context), content_type = 'application/json') #dict타입을 스트링으로 바꿔서 넘겨주는 것
#json.dumps(context)를 json형으로 보낸다는 것, 제어권을 자바스크립트로 다시 넘긴 것, xml 파일을 넘길 떄는 content_type = 'application/xml'
def func2(request): #파이썬에도 배열은 있지만 잘 사용안함. 데이터분석에서 선형대수를 지원하지않아서 NumPy의 배열을 쓰는 것
datas = [
{'irum':'고길동', 'nai':25},
{'irum':'신길동', 'nai':35},
{'irum':'나길동', 'nai':45}
]
return HttpResponse(json.dumps(datas), content_type = 'application/json')
3. html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
//web의 f12에서는 ajax처리 후의 코드는 볼 수 없다
$(document).ready(function(){
//alert("aaa");
$("#btn1").click(function(){
//alert("1");
//ajax요청
let msg = $("#txtMsg").val();
//alert(msg);
$("#showData").empty();
$.ajax({//대표적인 ajax함수 = jquery.ajax
url: 'startajax',
type:'get',
data:{'msg':msg}, //다른 형식: msg = msg => 'msg'에 홍길동을 가져가는 뜻
dataType:'json',//= return type
success:function(data){ //기다리고있다가 data가 넘어오면 작동 -> callback
//alert(data);
//데이터가 여러개일 수 있으니깐 for문으로 받음
let str = ""; //let은 지역, 전역 확실히 구분, var는 구분안함
for(let k in data){
//alert(k);
str = k + ':' + data[k];
// <=> var str = k + '<br>' + data[k];
}
str += "<br><b>"+data["key"]+"</b>"
$("#showData").html(str);
},
error:function(){
$("#showData").text("에러")
}
});
});
$("#btn2").click(function(){
//alert("2");
//$("#showData2").html("<i>1</i>")
$("#showData2").empty();
$.ajax({
url: 'goajax',
type:'get',
dataType:'json',
success:function(data){
//alert(data);
let str = "";
$.each(data, function(index, entry){//서버에서 데이터를 보낼 때 0부터 시작하는 index를 함께 넘기기 때문에 쓰든 안쓰든 우선 표시
//entry는 넘어오는 값
str += entry['irum'] + ' , '+ entry['nai']+ '<br>';
});
$("#showData2").html(str);
},
error:function(){
$("#showData2").text("에러")
}
});
});
});
</script>
</head>
<body>
<h1>ajax test</h1>
자료입력: <input type="text" id="txtMsg" value="홍길동">
<br>
<button id="btn1">버튼1 클릭</button>
<br>
<div id="showData">실습결과1</div>
<hr>
<button id="btn2">버튼2 클릭</button>
<br>
<div id="showData2">실습결과2</div>
</body>
</html>
<db연결 예시>
1. urls.py
from django.contrib import admin
from django.urls import path
from myajax import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.MainFunc),
path('calldb', views.ListDbFunc),
]
2. views.py
from django.shortcuts import render
from myajax.models import Sangdata
from django.http.response import HttpResponse
import json
# Create your views here.
def ListDbFunc(request):
sdata = Sangdata.objects.all()
datas = []
for s in sdata: #json으로 데이터를 받기 때문에 dict타입으로 받음
dic = {'code':s.code, 'sang':s.sang, 'su':s.su, 'danga':s.dan}
datas.append(dic)
return HttpResponse(json.dumps(datas), content_type = 'application/json')
3. html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
//callback
$(document).ready(function(){
$("#btnOk").click(function(){// = .bind("click") =.on("click")
$("#showData").empty();
$.ajax({
url:'calldb',
type:'get',
dataType:'json',
success:function(data){
//alert(data);
let str = "<table border = '1'><tr><th>코드</th><th>품명</th><th>수량</th><th>단가</th></tr>";
let count = 0;
$.each(data, function(ind, entry){
str += "<tr>";
str += "<td>" + entry['code']+"</td>";
str += "<td>" + entry['sang']+"</td>";
str += "<td>" + entry['su']+"</td>";
str += "<td>" + entry['danga']+"</td>";
str += "</tr>";
count += 1;
});
str += "</table>";
$("#showData").append(str);
$("#showData").append("건수: "+ count);
},
error:function(){
$("#showData").text("에러");
}
});
});
});
</script>
</head>
<body>
<button id="btnOk">상품자료 출력(Ajax)</button>
<div id="showData"></div>
<br>
<br>
<hr>
관리자 : 홍길동
</body>
</html>
9. 템플릿 언어(template language) (0) | 2021.05.29 |
---|---|
7. html파일 (0) | 2021.05.29 |
6. paging 처리 (0) | 2021.05.29 |
5. 세션 session (0) | 2021.05.29 |
4. Django 설정 파일 (0) | 2021.05.11 |