【问题标题】:How to refresh a div of a page to load the updated value from the database?如何刷新页面的 div 以从数据库加载更新的值?
【发布时间】: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 的初学者,所以很难找出可以解决这个问题的代码。

【问题讨论】:

标签: javascript html django ajax


【解决方案1】:

假设您想在单击该标题时更新计数,我会做这样的事情。 Fetch API

function ViewCountRefresh(){
    //assuming you are using es6 and you are not supporting IE11
    fetch('http://example.com/movies.json')
        .then(function(response) {
            return response.json();
        })
        .then(function(countViews) {
                var viewcountrefreshDiv = document.querySelector('#viewcountrefresh');
                var paragraphTag = viewcountrefreshDiv.querySelector('p');
                paragraphTag.innerText = countViews;
        });
}

【讨论】:

  • 嘿@lucio-poveda,我正在尝试按照您在此处提到的内容,但问题仍然存在。我已经用所有必需的代码更新了问题,请你帮我解决这个错误。
猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
相关资源
最近更新 更多