【问题标题】:Django render template on AJAX successAJAX成功的Django渲染模板
【发布时间】:2018-11-30 09:04:55
【问题描述】:

我正在尝试制作一个基于 Django 的 Web 应用程序,该应用程序接受用户输入并执行在近五到十分钟内完成的繁重后台任务。后台任务完成后,很少有参数提供给模板进行渲染。一切正常,然后页面加载。

但是当我尝试为此使用 AJAX 时,由于后台繁重的处理,页面加载这么长时间似乎不太好,我无法弄清楚如何重新加载页面(虽然我是能够在完成时显示警报,但我想重新渲染页面而不是这个)

这是我的views.py代码:

def index(request):
    #All Background process code goes here
    return render(request, 'form.html', {'scanResults' : scanResults, 'context_list' : context_list, 'scanSummary' : scanSummary})

这是我的 AJAX 调用

<script type="text/javascript">
$(document).on('submit','#scanForm', function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: '/scanner/',
        data: {
            email: $('#email').val(),
            context: $('#context').val(),
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
        },
        success:function(response){
            alert('Scan Completed');
            location.reload();
        }
    });
});

我不知道,我应该在成功函数中写什么来重新加载索引函数返回到模板的页面。

我的主要动机是显示一个进度条,告诉后台进程的进度(我还没有实现代码),一旦进程完成,刷新页面并响应。

谢谢

【问题讨论】:

    标签: ajax django


    【解决方案1】:

    如果您想检查进程的进度,您可能需要轮询机制 作为解决方案。
    这要求您有一个具有状态的模型来确定您的扫描是否 仍在进行中或已成功。

    由于您将重新加载页面以显示结果,因此您应该 index 视图中的逻辑以返回不同的模板或上下文 用于用户尚未开始扫描以及扫描成功的时间。

    from django.http import JsonResponse
    
    def index(request):
    
        if status == 'success':
            # `status` may come from a Model which has a state .
            # If `status` is 'success' this means that your scanning has 
            # finished so you can have a different page or update context_list
            # based on success data.
    
        # Display input form
        form = scannerForm()
    
        return render(request, 'form.html', {
            'form': form,
            'context_list' : context_list,
            'scanSummary' : scanSummary
        })
    

    您需要一个视图来持续检查扫描状态并返回 JSON 响应。

    def scanner(request):
        #All Background process code goes here
    
        form = scannerForm(request.POST)
        status = form.perform_task()
        # During the task, your Model state should also be 
        # updated and return the status whether it is success, pending or failed etc..
    
        return JsonResponse({
            'status': status,
        })
    

    运行 ajax 轮询以检查 scanner 视图。

    <script type="text/javascript">
    
    $(document).on('submit','#scanForm', function(e){
      e.preventDefault();
      checkScanStatus();
    });
    
    function checkScanStatus () {
      $.ajax({
        type: 'POST',
        url: '/scanner/',
        data: {
          email: $('#email').val(),
          context: $('#context').val(),
          csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        },
        success: handleCheckScanStatus,
        error: handleScanError
      });
    }
    
    
    function handleCheckScanStatus (result) {
        if (result.status == 'success') {
          // Reload the page and display the condition you set for 'success' state
          // on the `index` view.
          location.reload();
        } else {
          // Show progress bar indicating that the process running in the background
          const interval = 5000; // Five seconds
          window.setTimeout(checkScanStatus, interval);
        }
    }
    
    
    function handleScanError (response) {
      console.error(response)
    }
    </script>
    

    我建议查看 django celery 的异步任务和 django-fsm 的转换模型状态。

    如果你只想要一个简单的加载器而不需要检查你的后台任务的具体状态,你可以使用jQuery AJAX的beforeSend方法来显示一个进度条,直到AJAX请求完成。

    【讨论】:

    • 这并没有解释如何使用新的上下文重新渲染页面。 location.reload()关于成功就不一样了
    猜你喜欢
    • 2022-09-27
    • 2018-11-25
    • 2015-06-23
    • 2022-07-22
    • 1970-01-01
    • 2018-05-20
    • 2018-11-05
    • 2021-02-26
    • 1970-01-01
    相关资源
    最近更新 更多