使用django模板中的ajax刷新div

时间:2017-06-14 09:57:28

标签: jquery ajax django

我尝试过几个类似问题的解决方案。但它们都不适合我。我是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>

我需要刷新&#34;结果&#34; 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)

1 个答案:

答案 0 :(得分:0)

you can do it only with js, using trick, you can call new version of current page, and replace only $('#result') content. (with same way work lazy_loading) something like that:

<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>