파이썬 장고 + AJAX 연동 문제입니다.
조회수 839회
AJAX + DJANGO를 이용해 화면을 수동으로 새로고침 하지 않아도 자동으로 값이 계속 변경되게 만들어보려고 합니다.
이럴 경우 코드를 어떻게 작성해야할지 너무 막막하여 질문올립니다.
templates/sign/index.html
<html>
<meta charset="UTF-8">
<body>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="Context">This is original</div>
<script type="text/javascript">
function ajaxTest(){
$.ajax({
type : "GET",
url : "sign/",
dataType : "text",
error : function() {
alert('통신실패!!');
},
success : function(data) {
$('#Context').html(data);
}
});
}
playAlert = setInterval(function() {
ajaxTest();
});
</script>
</body>
</html>
views.py
import os
from django.shortcuts import render
from django.shortcuts import HttpResponse
def AjaxRespon(request):
#return HttpResponse('<div id = "Context">테스트</div>')
key = open(os.path.join(os.path.dirname(__file__), 'data'), mode='r', encoding='utf-8').read()
context = {'key':'<div id = "Context">{}</div>'.format(key)}
return render(request, 'sign/index.html', context)
urls.py
from . import views
from django.urls import path
urlpatterns = [
path('sign/', views.AjaxRespon, name='index')
]
미치겠네요 views.py에서 HttpResponse를 이용할 경우 정상적으로 작동은 하나 동적으로 움직이질 않고, 그렇다고 render를 쓰니 그냥 정적인 페이지가 되버려서 쓸수가없네요...
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
코드대로라면 사실
AjaxRespon(request)
은 단순text/html
을 반환하면 되는 메소드입니다. 이런걸 시도해 보세요.def AjaxRespon(request): # 중간 생략 return '<div id = "Context">{}</div>'.format(key)
- JsonResponse를 이용하여 값을 전달하고 이런식으로 해서 해결했습니다. 알 수 없는 사용자 2020.1.24 11:25
- 답변 감사합니다. 알 수 없는 사용자 2020.1.24 11:25
댓글 입력