This is a problem with Python Django + AJAX linkage.

Asked 2 years ago, Updated 2 years ago, 61 views

You want to use AJAX + DJANGO to make sure that the value will continue to change automatically without having to manually refresh the screen.

In this case, I don't know how to write the code, so I'm asking you a question.

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('Communication Failure!!');
        },
        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):
    #returnHttpResponse ('<divid = "Context">Test</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')
]

I'm going crazy. If I use HttpResponse on views.py, it works normally, but it doesn't move dynamically, but I can't use it because it just becomes a static page when I use a render...

python django database

2022-09-22 17:59

1 Answers

According to the code, AjaxRespon(request) is actually a simple text/html. Try something like this.

def AjaxRespon(request):
    # an intermediate omission
    return '<div id = "Context">{}</div>'.format(key)


2022-09-22 17:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.