【问题标题】:Reload/Refresh 2 separate id in an Django HTML template using Ajax Javascript如何使用 Ajax Javascript 为 Django 项目刷新 HTML 中的多个 id
【发布时间】:2022-10-04 17:44:56
【问题描述】:

我正在尝试发送 2 个响应,以便可以在不刷新整个页面的情况下更新 HTML 的 2 个部分。

这是阿贾克斯:

$.ajax({
    type:\'POST\',
    url:\'{% url \'app:bla\' %}\',
    data:{\'active\' : status, \'csrfmiddlewaretoken\':\'{{csrf_token}}\'},
    dataType:\'json\',
    success:function(response){
        $(\'#start\').html(response[\'form\']),
         //I am trying to refresh #log_form also the same way same #start gets refreshed                       
        //$(\'#log_form\').html(response[\'form2\']),
        //What else should I add here to change the id of another part of the html called #log_form
        console.log($(\'#start\').html(response[\'form\']));
    },
    error:function(rs, e){
        console.log(rs.responseText);
    },
});

这是解释我在做什么的部分观点

def change_status(request, id):
    if request.is_ajax() and request.method == \'POST\':
        if request.POST.get(\'active\') == \'true\':
            # .......do stuff
            context = {
                \'active\': \'\'
            }
            html = render_to_string(\'app/button.html\', context,request=request)
            html2 = render_to_string(\'app/log_form.html\', context,request=request)
            return JsonResponse({\'form\': html}, {\'form2\': html2})
        else:
            print(\"Fail\")
    else:
        print(\"Fail\")

现在,当我单击某个按钮 #start 时,只会刷新而不是整个页面。

我的问题:我怎样才能让#log_form 也与#start 同时刷新。

    标签: javascript django ajax


    【解决方案1】:

    添加在单击某个按钮#start 时如何触发$.ajax() 的代码。您需要添加event.preventDefault() 以避免按钮的默认操作,这可能是整个页面重新加载的原因。在同一个地方你可以触发#log_form的动作,不管它是什么

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-12
      • 2020-05-29
      • 2012-03-13
      • 2022-01-23
      • 2013-09-29
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      相关资源
      最近更新 更多