【发布时间】:2021-01-04 19:40:17
【问题描述】:
我在我的一个小型博客项目的帖子中有一个 viewcount 功能,它计算特定博客的查看次数,但在查看特定博客后,viewcount 的值保持不变,直到整个页面被刷新。因此,我正在尝试找出一种方法来仅刷新包含 viewcount 值的 div 部分的那部分。
这是我需要的 html 代码部分:-
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<h2><a class="article-title" href="{% url 'post-detail' post.slug %}" onclick="ViewCountRefresh()">{{ post.title }}</a></h2>
<div class="article-metadata" id="viewcountrefresh">
<a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a>
<div class="float-right">
<small class="text-muted">Category</small>
<small class="text-muted">{{ post.date_posted }}</small>
</div>
<img style="height:19px; width:18px; float:right;" src="{% static "blog/viewicon.png" %}"><p id="viewcountrefresh" style="float: right; display: inline !important;">{{post.view_count}}</p></img>
</div>
<p class="article-content">{{ post.content|truncatechars:200|safe }}</p>
</div>
</article>
{% endfor %}
这是我的views.py 文件:-
class PostDetailView(DetailView):
model = Post
def get_object(self):
obj = super().get_object()
obj.view_count += 1
obj.save()
return obj
这是 urls.py 文件:-
from django.urls import path
from .views import (
PostDetailView,
home,
)
urlpatterns = [
path("", home, name="blog-home"),
path("post/<slug:slug>/", PostDetailView.as_view(), name="post-detail"),
]
我正在尝试刷新包含 id viewcountrefresh 的 div 部分的内容,以便在访问任何博客时,然后我回到我的主页,我会从数据库中获取 viewcount 的更新值。
这是js脚本:-
function ViewCountRefresh(){
...
...
...
}
我是 javascript 和 ajax 的初学者,所以很难找出可以解决这个问题的代码。
【问题讨论】:
-
这能回答你的问题吗? Update data on a page without refreshing
标签: javascript html django ajax