gpt4 book ai didi

python - 使用 Django 和 AJAX 的动态 HTML 页面的最小示例

转载 作者:行者123 更新时间:2023-11-28 02:27:38 24 4
gpt4 key购买 nike

我引用了以下帖子:

尽管有两个帖子和不错的答案,但我仍在努力为诉诸 Django 和 AJAX 的动态 HTML 页面构建一个最小的工作示例。

我必须遵循以下代码:

模型.py

from django.db import models


class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^get_more_tables', views.get_more_tables, name='get_more_tables')
]

views.py

from django.shortcuts import render
from .models import Question

def index(request):
a = Question.objects.order_by('-pub_date')
context = {'questions': a}
return render(request, 'polls/index.html', context)

def get_more_tables(request):
a = Question.objects.order_by('-pub_date')
context = {'questions': a}
return render(request, 'polls/get_more_tables.html', context)

index.html

<html>
<body>

<table id="_appendHere">
<tr><td> text </td></tr>

{% for a in questions %}
<tr><td> {{ a.question_text }} </td></tr>
{% endfor %}

</table>
</body>
</html>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: "{% url 'get_more_tables' %}",
data: {'append_increment': append_increment}
})
.done(function(response) {
$('#_appendHere').append(response);
append_increment += 10;
});
}, 1000)

get_more_tables.html

{% for a in questions %}
<tr><td> {{ a.question_text }} </td></tr>
{% endfor %}

我有以下问题:

  • 根据 Console Error with Ajax: ReferenceError: $ is not defined ,我需要在 js 脚本中设置 js.file。如果我不这样做,我会收到“ReferenceError: $ is not defined”错误。为什么会这样,特别是因为这对于前面提到的帖子来说不是必需的?
  • 如果我运行 http://localhost:8000/polls/ , 什么都没发生。我假设,当我使用

    q2 = Question(question_text="What's up4?", pub_date=timezone.now())q2.save()

通过 python manage.py shell,应该显示整个内部数据库。然而,什么也没有发生。当我手动刷新网站时,会显示所有条目。

  • Mozilla 的检查器控制台没有显示任何条目。 Mozilla 的网络控制台确实显示访问了/pools 和外部 js 文件。但是,没有显示 1s 间隔的连续访问(不确定是否应该是这种情况)。

最佳答案

您的 HTML 无效,原因有几个。

首先,您将脚本 block 放在结束 </html> 之外标签。这意味着它在文档本身之外,浏览器可能无法读取。

更重要的是,您没有将代码放在适当的脚本元素中。您有一个开始标记,但您使用它通过 src 引用外部 jQuery 库属性。你根本没有结束标签

您需要将 jQuery 引用放在它自己的元素中,并为您自己的脚本使用适当的开始和结束标记。

<html>
<body>
<table>
...
</table>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: "{% url 'get_more_tables' %}",
data: {'append_increment': append_increment}
})
.done(function(response) {
$('#_appendHere').append(response);
append_increment += 10;
});
}, 1000)
</script>
</body>
</html>

关于python - 使用 Django 和 AJAX 的动态 HTML 页面的最小示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com