【问题标题】:Refresh a django subtemplate with javascript - reload only part of the page使用 javascript 刷新 django 子模板 - 仅重新加载页面的一部分
【发布时间】:2021-08-28 00:08:40
【问题描述】:

我正在尝试通过使用 js 调用视图来刷新子模板。尽管服务器被击中并且似乎返回了响应,但似乎什么也没发生。

目标是刷新包含的部分而不刷新整个页面。

小例子:

views.py

def ajax_view(request):
    context = {}
    context['data'] = 'data'
    return render(request, "test.html", context)// <-- reaches here, but no rendering

test.html

{{data}}

main.html

<script type="text/javascript">

    function getQuery() {
        var request = new XMLHttpRequest(),
        method = 'GET',
        url = '/ajax/';

        request.open(method, url);
        request.send();
    }
</script>

{% include "test.html" %} // <-- does not update

【问题讨论】:

    标签: javascript django


    【解决方案1】:

    在朋友的帮助下,我解决了这个问题。

    我将详细回答我的问题,因为我 100% 确定以后会有人需要弄清楚如何做到这一点。很高兴为您省去麻烦。

    我不得不改变我的心智模式来了解它是如何工作的。

    我仍然使用 javascript 向服务器发送请求,视图返回模板化的 HTML。

    但是,这是重要的部分,我所做的是获取呈现的 HTML(从响应中,返回 return render(response, "your_template.html", context) 的内容)并将我页面的那部分替换为该 HTML。

    这里是 Javascript。

    function getQuery(item) {
      // Sends a request to the API endpoint to fetch data
    
      let request = new XMLHttpRequest();
      let method = 'GET';
      let query = // omitted
    
      let url = '/ajax/?' + query;
      request.open(method, url);
      request.onload = function () {
        // the response is the rendered HTML
        // which django sends as return render(response, "your_template.html", context)
        let myHTML = request.response;
        // This is the important part
        // Set that HTML to the new, templated HTML returned by the server
        document.getElementById('flex-container-A').innerHTML = myHTML;
      };
      request.send();
    }
    

    为了完整起见,以下是视图: views.py

    def ajax_view(request):
        """
        Server API endpoint for fetching data
        """
    
        context = {}
        queryset = Form.objects
    
        if request.method == 'GET':
            query = request.GET.get('q')
    
            # do some stuff and get some data
        
            context['data'] = data
    
            return render(request, "my_template.html", context)
    

    希望对您有所帮助!这是一种常见的模式,但并不经常如此明确地提及。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 2021-11-16
      相关资源
      最近更新 更多