【问题标题】:how to refresh in a div values from a model with jquery .ajax() to django如何使用 jquery .ajax() 将模型中的 div 值刷新到 django
【发布时间】:2012-05-10 15:15:09
【问题描述】:

我有一个返回 3 个模型的链接对象的视图

def test(request):
    output=itertools.chain(
        model1.objects.all(),
        model2.objects.all(), 
        model3.objects.all()
    )

    return render_to_response('test.html', {'output':output})

在 html 中,我添加了一个锚点和一个 jQuery 脚本,它应该将 #output 替换为来自 model1 的新值

<html>
<head>...</head>
<body>
<script>
    $(document).ready(function() {

        $("#switch").click(function() {
            $.ajax({
                url: $(this).attr("href"),
                success: function(result) {
                    //whatever I put here is not triggered
                }
             });
        });
    });
</script>

    <a id="switch" href="?model=1">switch to model 1</a>

    <div id="output">
        {% for item in output %}
            <div id="{{item}}">
                {{item}}
            </div>
        {% endfor %}
    </div>
</body>
</html>

我尝试将 div#output 放入单独的模板 output.html 并修改 views.py 如下:

def test(request, template='test.html'):

    if request.GET.get('model'):
        output=model1.objects.all()
    else:
        output=itertools.chain(
           model1.objects.all(),
           model2.objects.all(), 
           model3.objects.all()
        )

    if request.is_ajax(): template='output.html'

    return render_to_response(template, {'output':output})

但是每次我点击链接时,整个页面都会刷新(使用来自 model1 的新值)。

Opera 只返回 output.html

为此苦苦挣扎超过 3 天,我是 Ajax 新手,这让我感到非常困惑。

我希望有人能解释一下!

【问题讨论】:

    标签: django jquery django-views


    【解决方案1】:

    首先,确保您的视图正常工作,并且在直接访问该 url 时获得预期的 HTML 输出(您可能还想暂时注释掉 if request.is_ajax())。

    然后,尝试在您的 ajax 调用中使用 jQuery.html() 方法替换 #output div 的内容。这是一个带有一些动画的示例:

    $.ajax({
    
        ...
        success: function( returnedData ) {
            $("#output").css("color", "red").fadeOut(500, function() {
                $("#output").html(returnedData);
                $(this).css("color", "green").fadeIn(500);
            });
        }
    

    另外,尝试使用 Firebug/Chrome 开发者工具监控您的 ajax 调用 - 这两种工具都可以让您快速确定问题。

    【讨论】:

    • 感谢您的提示...问题是从未触发成功功能,因为我没有覆盖 a 的默认操作!
    【解决方案2】:

    感谢 Daniel Rosman 的提醒,我不得不阻止 a#switch 的默认操作。它现在就像黄油一样!

    这是最初的问题:how to access jQuery.ajax() get parameters in Django views

    【讨论】:

      猜你喜欢
      • 2014-07-14
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      相关资源
      最近更新 更多