【问题标题】:Refreshing div using ajax in a django template在 Django 模板中使用 ajax 刷新 div
【发布时间】:2017-11-16 09:47:35
【问题描述】:

我尝试在几个类似问题中实施解决方案。但他们都没有为我工作。我是 django 的新手。我正在尝试构建一个获取 whois 记录的应用程序。

我的模板文件是:

<form action = "{% url 'whoisrec:index' %}" method = "post">
  {% csrf_token %}
  <input name = "domain" type = "text" value = "{{domain}}" />
  <button name = "submit" type = "submit" value = "Go" />
</form>

<div id = "result">
    {{text|linebreaks}}
</div>

每次输入新域时我都需要刷新“结果”div,而不是刷新整个页面。

我正在使用的脚本:

<script>
  $(document).ready(function() {
    $("#submit").click(function() {
      $.ajax({
        url: '{% url 'whoisrec:index' %}',
        success: function(data) {
          var html = $(data).filter('#result').html();
          $('#result').html(html);
        }
      });
    });
  });
</script>

我的看法:

def index(request):
    try:
        domain = request.POST['domain']
        requested = True
    except:
        return render(request, 'whoisrec/index.html')
        requested = False
    w = whois.whois(domain)
    text = w.text
    context = { 'domain' : domain,
                'text'  : text,
                'flag'  : requested
              }
    return render(request, 'whoisrec/index.html',context)

【问题讨论】:

  • 你为什么不用$.load

标签: jquery ajax django


【解决方案1】:

你只能用 js 来做,使用技巧,你可以调用当前页面的新版本,并且只替换 $('#result') 内容。 (以同样的方式工作lazy_loading)类似的东西:

<script>
    $(document).ready(function() {
        $("button.add-comment-button").click(function() {
            $.get(window.location.href,{},function(response){
                var new_version = $('<div></div>').append(response);
                var new_result = new_version.find('#result');
                if(new_result.length){
                    $('#result').html( new_result.html() );
                    console.log('update');
                }else{
                    console.log('something wrong');
                }
            });
        });
    });
</script>

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 1970-01-01
    • 2018-10-23
    • 2011-04-16
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2012-05-10
    • 2014-04-23
    相关资源
    最近更新 更多