728x90
이걸 하고싶었던건데 .. 드디어 성공했다. 어제 한시간정도 팀원에게 Django 관련 강의? 를 듣고 오늘 직접 서버 연결 후 해봤는데 성공했다.. 후 이제 URL 바꾸는 거만 하면 내가 처음에 하려고 했던 모든 게 끝난다. Ajax 드디어 탈출하나 싶다 ㅜ 너무 힘들다
로직은 이렇게 되어있다.
1 Django 서버를 돌린다 (Django 템플릿 사용 X)
2 ex) 127.0.0.1/test 라는 URL을 하나 만들고, views.py에 127.0.0.1/test와 연결된 view를 만든다.
def list(request): ~~ .. 여기선 return render(request, 'list.html') 로 했다.
3 html 내에 script를 짜서, 127.0.0.1/test를 찔러서 데이터를 가져온다. (여기까지 성공)
4 들어올 데이터 html에 CSS작업을 통해 예쁘게 만들기만 하면 됨
HTML + JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id='listButton'>리스트 출력</button>
<br/>
<div id='example'></div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<!-- jQuery 라이브러리 사용 -->
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<script>
$('#listButton').click(function() {
$.ajax({
type: "GET",
url:"{% url 'list' %}", // list url을 불러옴
dataType: 'html', // list의 형태는 html
success: function(data){ // 성공했을 때 일단 good을 alert로 띄운다.
alert('good');
$('#example').html(data) // 그 이후에 example div에 list html의 data를 가져온다.
},
error: function(request, status, error){ // 실패했을 때 bad alert, 에러가 무엇이었는지, 그리고 간단한 html 출력
alert('bad');
alert(error);
$('#example').html('AJAX 통신에 실패했습니다.');
}
})
})
</script>
</body>
</html>
views.py in app
from django.shortcuts import render
from django.http import HttpResponse
import json
# Create your views here.
def main(request):
return render(request, 'index.html')
def list(request):
return render(request, 'list.html')
# def ajax(request): 이 부분은 JSON을 이용해서 Data만 그대로 가져오는 과정임
# data = {
# 'Organization': [
# {
# "name": "Sangmin Park",
# "github": "steadily-worked"
# },
# {
# "name": "Woosik Kim",
# "github": "well-balanced"
# },
# {
# "name": "Hyeonsu Lee",
# "github": "incleaf"
# },
# {
# "name": "Hoseon Lee",
# "github": "indante"
# }
# ]
# }
# response = json.dumps(data)
# return HttpResponse(response)
# return HttpResponse(json.dumps(data), content_type='application/json')
# content를 context에 담고 content_type을 json.dumps(context)가 json화 시켜준다. 그리고 만든 걸 다시 JS에 넘겨준다.
urls.py in app
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.main, name='main'),
# ajax 통신요청 경로
# path('ajax/', views.ajax, name='ajax'),
path('list/', views.list, name='list'),
]
뭐 절대적인 난이도가 어렵다고 볼 수는 없는데, 익숙하지 못함이 문제였던 것 같다. ㅋㅋ
이제 진행중인 프로젝트의 파일에 Django 서버 세팅 후 시도해봐야겠다.
'today i learned' 카테고리의 다른 글
| today i learned 9/12 (0) | 2020.09.13 |
|---|---|
| today i learned 9/11 (0) | 2020.09.13 |
| today i learned 9/9 서버 없이 Ajax 비동기 통신하기 (0) | 2020.09.09 |
| today i learned 9/8 (0) | 2020.09.08 |
| today i learned 9/7 (0) | 2020.09.08 |