2017-06-14 42 views
0

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

我的模板文件是:

<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) 
+0

为什么不使用'$ .load'? –

回答

0

你只能用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>