简体   繁体   English

Django使用Javascript包含模板

[英]Django include template using Javascript

I came from a Rails background thus the question may seem stupid. 我来自Rails背景,因此这个问题似乎很愚蠢。 In Rails, when we create a Ajax request, then we can update a view by rendering a partial using the javascript selector like the following: 在Rails中,当我们创建Ajax请求时,可以通过使用javascript选择器呈现部分视图来更新视图,如下所示:

$("#dashboardEmails").html("<%=j render partial: 'emails', locals: {emails: @emails} %>");

How can I do that in Django template? 如何在Django模板中做到这一点? I've tried the following: 我尝试了以下方法:

$.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize() + "&submit=connect",
        success: function (data) {
          if(data['tables'].length > 0){
            $('#data-connection-info').html("{% include 'projects/connection_info.html' with data='"data"' %}");
          }
          console.log(data);
        },
        error: function (data) {
          console.log("Error");
        }
});

Here, I want to update the view with a template projects/connection_info.html , also passing a javascript variable ( data ) to the template using with . 在这里,我想使用模板projects/connection_info.html更新视图,并使用with将JavaScript变量( 数据 )传递给模板。 But it is not working. 但这是行不通的。

Any idea how can I achieve that? 知道如何实现吗?

UPDATE UPDATE

I passed the template from the view like: 我从如下视图传递了模板:

template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')

Then in the ajax success function updates the DOM: 然后在ajax成功函数中更新DOM:

success: function (data) {
          $('#data-connection-info').html(data);
 }

In this way the problem is solved. 这样就解决了问题。 :) :)

I passed the template from the view like: 我从如下视图传递了模板:

template = render_to_string('projects/connection_info.html', json_data)
return HttpResponse(json.dumps(template), content_type='application/json')

Then in the ajax success function updates the DOM: 然后在ajax成功函数中更新DOM:

success: function (data) {
          $('#data-connection-info').html(data);
 }

In this way the problem is solved. 这样就解决了问题。 :) :)

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

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