简体   繁体   English

使用AJAX获取Django视图数据

[英]Fetch Django view data with AJAX

Currently I am building an app which update the main page's data via AJAX. 目前,我正在构建一个可通过AJAX更新主页数据的应用程序。 Based on this question I used (see code/1/ below) ajax to refresh my page. 基于这个问题,我使用了ajax(请参见下面的代码1/1 /)来刷新我的页面。 My other aim is to catch just certain variable from the view and use as a JS variable. 我的另一个目标是从视图中仅捕获某些变量并将其用作JS变量。 If I use only Django template variable in the AJAX request my variable not refreshig. 如果我在AJAX请求中仅使用Django模板变量,则我的变量不刷新。

First attempt: 第一次尝试:

Django view: Django视图:

def fetch_data (request):

    query_1=Objects.all()
    query_2=Objects.all()

    #From these  queries I colect data and push  them to lists.

    context= {
                'variable_1': variable_1,
                'variable_2': variable_2,
                'time_variable': time_variable #changing in every minute
           }

    return render(request, 'app/index.html', context)

AJAX: AJAX:

Here I use the AJAX request. 在这里,我使用AJAX请求。 I run it in every minute to realod my page my page. 我每分钟运行一次,以重新整理我的页面。 My problem is that I want to load just let's say the time_variable to use it again within AJAX. 我的问题是,我只想加载time_variable以便在AJAX中再次使用它。 If I use it like a single template variable ( {{time_variale|safe}} ) when the AJAX reloading I get the same variable again and again and not a new one because of the refreshing. 如果在重新加载AJAX时像单个模板变量( {{time_variale|safe}} )一样使用它,我会一次又一次获得相同的变量,而不会因为刷新而获得新的变量。 How gen I catch the Django variable? 我如何捕捉Django变量?

setInterval(function(){
    if(new Date().getSeconds() === 0) {     
        $.ajax({
        url:'{% url 'fetch_data' %}',
        success: function (data){
              $('body').html(data); #This working, the data refreshing
              var="{{time_variable|safe}}"; #Here I always get the same in every minutes despite the variable get new value in every minute in the view.
           }
        });
  }
},1000)

Solution 1 解决方案1

Fetch data from the server in JSON format and update the variable and HTML. 从服务器以JSON格式获取数据并更新变量和HTML。 A new view is needed to provide data to AJAX request. 需要一个新的视图来向AJAX请求提供数据。

    setInterval(function(){
    if(new Date().getSeconds() === 0) {     
        $.ajax({
        url:'{% url 'fetch_data' %}',
        success: function (data){
              response_json = JSON.parse(data)

              $('body').html(response_json.html_data); #This working, the data refreshing
              var=response_json.variable_value; #Here I always get the same in every minutes despite the variable get new value in every minute in the view.
           }
        });
    }
   },1000)

Solution 2 解决方案2

Reload the page in intervals, this not a recommended suggestion though as it just degrades performance of back-end and inefficient. 定期重新加载页面,尽管这会降低后端性能并降低效率,但不建议这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM