Updating info on html page using Ajax in Django

时间:2017-11-13 06:45:10

标签: javascript jquery html ajax django

I have a problem with Ajax and how can I update info on my HTML page without reloading it.
So, I have a function in my views.py file:

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

And I just use variables from {context} in my header.html file. And the question is - how can I perform index function and send new variables to my header.html file without reloading it?

1 个答案:

答案 0 :(得分:3)

首先,创建一个新端点,以获取所需格式的数据。我更喜欢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文本或类名称或样式等。