【问题标题】:Django: Pass context into a template using AjaxDjango:使用 Ajax 将上下文传递到模板中
【发布时间】:2021-10-26 17:23:21
【问题描述】:

我知道有人问过这个问题here

但是 anwser 不太适合我的需要。 在我的 Django 项目中,我想将上下文数据作为字典提供给我的模板。 像平常一样:return render(request, 'the.html', context)

我首先在没有任何 ajax 的情况下构建了我的整个网站,因此在成功时使用 ajax HTML 完全重写将是相当多的工作:

$("#div_to_update").html( -- completely rewrite already written html code to fit the new ajax -- ) 

有没有办法更轻松地将上下文传递给 django 模板之类的?

$("#div_to_update").set_context(context_the_server_passed_to_ajax)

【问题讨论】:

    标签: django ajax


    【解决方案1】:

    好的,我知道怎么做:

    发送一个普通的 Ajax 请求,但在 JS 中进行:

    success: function (content) {
        $("#div1").html(content)
    }
    

    在你看来返回

    return render(request, 'the_file_to_render.html', context)
    

    这样,完整的 div1 将被渲染的具有上下文的部分替换

    【讨论】:

      猜你喜欢
      • 2018-10-04
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多