파이썬 장고 + 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 답변

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)