JAVASCRIPT: After sending Item to Database (POST) the window.location.reload() does not work. How to refresh the Data in HTML-Template?

huangapple go评论66阅读模式
英文:

JAVASCRIPT: After sending Item to Database (POST) the window.location.reload() does not work. How to refresh the Data in HTML-Template?

问题

我在YouTube上录制了一个教程。 Django,Python,HTML和JavaScript。一切都正常,除了window.location.reload()函数。

我尝试了一些解决方法,包括:

  • windows.reload(true)
  • window.href = window.href
  • location = self.location
    以及其他一些方法。

我有一种直觉,即刷新操作在刷新之前或在刷新期间执行。但我不确定。

目标是将输入的数据发送到数据库,然后刷新页面。

这是教程中的代码:

index.html(缩短版)

<body>
    <header>
        <h1>购物清单</h1>
        <div id="input-field">
            <label for="item-input">你想买什么?</label>
            <input type="text" name="item" id="item-input">
        </div>
        <button id="btn" onclick="addItem()">+</button>
    </header>
    <div id="item-table">
        {%  for row in all_items %}
        <div class="list-item">
            <input type="checkbox"> {{row.name}}
        </div>
        {% endfor %}
    </div>

    <script>
        function addItem(){
            let itemName = document.getElementById("item-input").value;
            let formData = new FormData();
            let token = '{{csrf_token}}';
            formData.append('itemName', itemName);
            formData.append('csrfmiddlewaretoken', token);
            fetch('/mylist/', {
                method: 'POST',
                body: formData
            });
            window.location.reload();
        };
    </script>
</body>
</html>

views.py

from django.shortcuts import render
from .models import ShoppingItem

# Create your views here.
def mylist(request):
    if request.method == 'POST':
        print('Received date: ', request.POST['itemName'])
        ShoppingItem.objects.create(name=request.POST['itemName'])
    all_items = ShoppingItem.objects.filter(done=0)
    return render(request, 'index.html', {'all_items': all_items})

models.py

from django.db import models
from datetime import date

# Create your models here.
class ShoppingItem(models.Model):
    createDate = models.DateField(default=date.today)
    name = models.CharField(max_length=200)
    done = models.BooleanField(default=False)

    def __str__(self):
        return '(' + str(self.id) + ') ' + self.name
英文:

I recode a Tutorial on Youtube.
Django, Python, HTML an Javascript.
Everthing works fine exept the window.location.reload() function.

I try some workarounds with

  • windows.reload(true),

  • window.href = window.href

  • location = self.location

and some more.

I have a hunch that the reload is executed before or during the code before the reload. But I do not know.

The goal is to send the data from the input to the database and only then refresh the page.

This ist the Code from the tutorial:

index.html (shortened)

&lt;body&gt;
    &lt;header&gt;
        &lt;h1&gt;Shoppinglist&lt;/h1&gt;
        &lt;div id=&quot;input-field&quot;&gt;
            &lt;label for=&quot;item-input&quot;&gt;Was m&#246;chtest du einkaufen?&lt;/label&gt;
            &lt;input type=&quot;text&quot; name=&quot;item&quot; id=&quot;item-input&quot;&gt;
        &lt;/div&gt;
        &lt;button id=&quot;btn&quot; onclick=&quot;addItem()&quot;&gt;+&lt;/button&gt;
    &lt;/header&gt;
    &lt;div id=&quot;item-table&quot;&gt;
        {%  for row in all_items %}
        &lt;div class=&quot;list-item&quot;&gt;
            &lt;input type=&quot;checkbox&quot;&gt; {{row.name}}
        &lt;/div&gt;
        {% endfor %}
    &lt;/div&gt;

   
    &lt;script&gt;

        function addItem(){
            let itemName = document.getElementById(&quot;item-input&quot;).value;
            let formData = new FormData();
            let token = &#39;{{csrf_token}}&#39;;
            formData.append(&#39;itemName&#39;, itemName);
            formData.append(&#39;csrfmiddlewaretoken&#39;, token);
            fetch(&#39;/mylist/&#39;, {
                method: &#39;POST&#39;,
                body: formData
            });
            window.location.reload();
        };

    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

views.py

from django.shortcuts import render
from .models import ShoppingItem

# Create your views here.
def mylist(request):
    if request.method == &#39;POST&#39;:
        print(&#39;Received date: &#39;, request.POST[&#39;itemName&#39;])
        ShoppingItem.objects.create(name = request.POST[&#39;itemName&#39;])
    all_items = ShoppingItem.objects.filter(done = 0)
    return render(request, &#39;index.html&#39;, {&#39;all_items&#39;:all_items})

models.py

from django.db import models
from datetime import date

#Create your models here.
class ShoppingItem(models.Model):
    creatDate = models.DateField (default=date.today)
    name = models.CharField (max_length =200)
    done = models.BooleanField(default=False)

    def __str__(self):
        return &#39;(&#39; + str(self.id) +&#39;) &#39; +self.name

答案1

得分: 0

尝试这样做:

async function addItem() {
  let itemName = document.getElementById("item-input").value;
  let formData = new FormData();
  let token = "{{csrf_token}}";
  formData.append("itemName", itemName);
  formData.append("csrfmiddlewaretoken", token);
  await fetch("/mylist/", {
    method: "POST",
    body: formData,
  });
  window.location.reload();
}
英文:

Try this:

async function addItem() {
  let itemName = document.getElementById(&quot;item-input&quot;).value;
  let formData = new FormData();
  let token = &quot;{{csrf_token}}&quot;;
  formData.append(&quot;itemName&quot;, itemName);
  formData.append(&quot;csrfmiddlewaretoken&quot;, token);
  await fetch(&quot;/mylist/&quot;, {
    method: &quot;POST&quot;,
    body: formData,
  });
  window.location.reload();
}

huangapple
  • 本文由 发表于 2023年2月18日 02:14:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487922.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定