【问题标题】:Updating info on html page using Ajax in Django在 Django 中使用 Ajax 更新 html 页面上的信息
【发布时间】:2018-04-25 18:57:41
【问题描述】:

我在使用 Ajax 时遇到问题,如何在不重新加载的情况下更新 HTML 页面上的信息。
所以,我的 views.py 文件中有一个函数:

def index(request):
  some stuff
  context = {
      some stuff
  }
  return render(request, "header.html", context)

我只是在我的header.html 文件中使用来自 {context} 的变量。问题是 - 如何在不重新加载的情况下执行索引功能并将新变量发送到我的 header.html 文件?

【问题讨论】:

  • Django 模板已转换为 html,因此您无法在不重新加载的情况下更新 html,但您可以在 ajax 成功函数中使用 javascript 更改一些 html,例如 element.innerhtml = "new stuff"
  • 如果你不擅长 ajax 我可以告诉你 - 在答案中 - 如何发送一个变量来查看然后更新 html

标签: javascript jquery html ajax django


【解决方案1】:

首先,创建一个新端点以获取所需的任何格式的数据。我更喜欢JSON

新端点

# views.py

from django.http import JsonResponse
def new_endpoint(request):
    """Returns `JsonResponse` object"""

    # you can change the request method in the following condition.
    # I dont know what you're dealing with.
    if request.is_ajax() and request.method == 'GET':
        # main logic here setting the value of resp_data

        resp_data = {
            'html': 'stuff',
            # more data
        }

        return JsonResponse(resp_data, status=200)

然后,您需要编写调用此端点的 AJAX 部分,使用方法、数据、标头等,最后定义 success 回调方法以获取所需的数据。

AJAX

var data = {};
$.ajax({
  url: '/your-new-endpoint-url',
  type: 'GET',
  data: data,
  dataType: 'json',
  success: function(resp) {
    $('#changingElement').html(resp.html);
  }
});

您可以从这个新端点发送任何类型的数据来更改任何元素的 html 文本或类名或样式等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2014-01-03
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多