Django 模板 更新部分内容

接手的项目前端全是用 Django 模板写的,有时需要页面上面的部分数据更新,使用 ajax 加接口的方式

home.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    {% load static %}
</head>
<body>
    <h3>标题</h3>

    <div id="ceshi">
        {% include 'data.html' %}
    </div>

    <div id="result1"></div>



    <button onclick="">点击了按钮</button>


    <script>
        $(document).ready(function () {
            $("button").click(function () {
                console.log("发生了单击事件!")
                $.ajax({
                    url: "http://127.0.0.1:8000/user/updatedata/",
                    type: "GET",
                    success: function (data) {
                        console.log("发送了接口请求");
                        console.log(data);
                        let ceshi=document.getElementById("ceshi");
                        ceshi.innerHTML= data;
                    }
                });
            })
        })


    </script>

</body>
</html>

data.html

<h2>{{ title }}</h2>

{%  for row in comment %}
    <div id="result">
        <p>{{row.comment_content}}</p>
        <p>{{row.comment_time}}</p>
    </div>

{% endfor %}

view.py

import json
from django.shortcuts import render
from django.template.loader import render_to_string
from django.http import HttpResponse
from .models import Comment

from django.http import JsonResponse

# Create your views here.


def home(request):
    # 处理请求的逻辑
    comment_query = Comment.objects.all()[:2]

    context = {
        "title": "上下文更新",
        "comment": comment_query
    }

    return render(request, "home.html", context=context)


def updatedata(request):
    # 处理请求的逻辑
    comment_query = Comment.objects.all()[:5]

    return render(request, "data.html", context={"comment": comment_query})

home.html 里面引用了 {% include 'data.html' %} data.html 这里的就是主数据,主要就是 直接将渲染后的html文本返回给前端,在对应位置使用 js.innerHTML 赋值即可

https://blog.csdn.net/y3332664073/article/details/138497340

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容