javascript 如何在 Django 模板中使用 Jquery/Ajax 正确刷新 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23856259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:41:50  来源:igfitidea点击:

How to correctly refresh a div using Jquery/Ajax in a Django template

javascriptjqueryajaxdjango

提问by Dirty Penguin

I have tried implementing the solution here, but I can't seem to get it working correctly.

我已尝试在此处实施解决方案,但似乎无法正常工作。

I have a div that is populated using a loop inside a Django template. Right below that, I have a input box where I can type some text and click Submit. The Submit action should trigger a Jquery script that gets a model object from the server. This model object should then be given to the div, and the div should subsequently be 'refreshed'. The intention here is that once the div is 'refreshed', the variable accessed by the for loop would have been updated, thus displaying the additional new results.

我有一个使用 Django 模板中的循环填充的 div。在它的正下方,我有一个输入框,我可以在其中输入一些文本并单击提交。Submit 操作应该触发一个从服务器获取模型对象的 Jquery 脚本。然后应将此模型对象提供给 div,然后应“刷新”该 d​​iv。这里的意图是一旦 div 被“刷新”,for 循环访问的变量就会被更新,从而显示额外的新结果。

My template code:

我的模板代码:

<h1> This is a Test Ajax Page</h1>
<div id="refresh-this-div">
    {% for comment in question.comment_set.all %}
        <p class="">{{ comment.body }}</p>
    {% endfor %}
        <input id="my-text-input-id" type="text" />
        <button type="submit" class="add-comment-button">Add</button>
    </div>
</div>

My Jquery:

我的jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        $("button.add-comment-button").click(function() {
            var com_body = $('#my-text-input-id').val();
            $.ajax({
                    url: '/test_login_url',
                    success: function(data) {
                    $('#refresh-this-div').html(data);
                    }
                  });
        });
    });
</script>

My view:

我的观点:

def test_login_url(request):
    question = Question.objects.get(id=1)
    com = Comment(question=question, body='This is a new Comment!')
    question.comment_set.add(com)
    return render_to_response('application/ajax_test_template.html', { 'question': question })

When I click the Submit button, the div is refreshed, however the div section that was refreshed now contains a copy of the h1 tag. As I click Submit multiple times, there are additional h1 tags and comments populated.

当我单击提交按钮时,div 会刷新,但是刷新的 div 部分现在包含 h1 标记的副本。当我多次单击提交时,会填充额外的 h1 标签和评论。

Here is an example of the page before clicking: before_clicking_submit

这是点击前的页面示例:before_clicking_submit

And here is an example after clicking Submit: after_clicking_submit

这是单击提交后的示例:after_clicking_submit

I've double checked that my implementation is as identical as possible to the solution I referenced earlier, however, I feel like I'm probably missing something simple here. What is the correct way to refresh the div with the new updated variable?

我已经仔细检查了我的实现是否与我之前引用的解决方案尽可能相同,但是,我觉得我可能在这里遗漏了一些简单的东西。使用新的更新变量刷新 div 的正确方法是什么?

回答by xjtian

The HTML returned from your test_login_urlview that you call via ajax includes the h1 element in your template. In your ajax success callback, you're loading that HTML, which includes the h1, into your refresh-this-divdiv, but you're not deleting the old h1 element that's sitting outside the container. A quick inspection of the DOM with the developer tools on your browser should illustrate what's going on.

从您test_login_url通过 ajax 调用的视图返回的 HTML包括模板中的 h1 元素。在您的 ajax 成功回调中,您将包含 h1 的 HTML 加载到您的refresh-this-divdiv 中,但您不会删除位于容器外的旧 h1 元素。使用浏览器上的开发人员工具快速检查 DOM 应该会说明发生了什么。

The easiest fix is probably to wrap the contents of your current template in a container.

最简单的解决方法可能是将当前模板的内容包装在容器中。

Template code:

模板代码:

<div id="refresh-this-div">
    <h1> This is a Test Ajax Page</h1>
    {% for comment in question.comment_set.all %}
        <p class="">{{ comment.body }}</p>
    {% endfor %}
    <input id="my-text-input-id" type="text" />
    <button type="submit" class="add-comment-button">Add</button>
</div>

Jquery:

查询:

$(document).ready(function() {
    $("button.add-comment-button").click(function() {
        var com_body = $('#my-text-input-id').val();
        $.ajax({
                url: '/test_login_url',
                success: function(data) {
                    // grab the inner html of the returned div 
                    // so you don't nest a new div#refresh-this-div on every call
                    var html = $(data).filter('#refresh-this-div').html();
                    $('#refresh-this-div').html(html);
                }
        });
    });
});