接手的项目前端全是用 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 赋值即可