首页 > 解决方案 > 使用 Django 仅更新 HTML 页面的一部分

问题描述

我有一个 HTML (annotator.html) 页面,其中上半部分包含一个表格。我有 JavaScript 代码,当用户选择表中的一行并将该数据显示在表下方的 div 中时,它会从数据模型中提取数据。

我的 Javascript 看起来像这样:

$('#radiological tbody').on( 'click', 'tr', function () {
    if ( $(this).hasClass('selected') ) {
        $(this).removeClass('selected');
    }
    else {
        //first unselect any other selected row
        dt_table.$('tr.selected').removeClass('selected');

        //then select row of interest
        $(this).addClass('selected');

        var rowIndex = dt_table.row('.selected')[0];
        var row = dt_table.rows(rowIndex);
        var id = row.data()[0]['id'];
        var url = '/report/' + id + '/';
        //window.location = url;

        $.ajax({
            url: url,
            type: 'get', // This is the default though, you don't actually need to always mention it
            success: function(data) {
            },
            failure: function(data) {
                alert('Got an error dude');
            }
        });

并正确填充我页面的下半部分,但也更新了上半部分。我只想刷新下半部分。

我的报告视图如下所示:

def report_page(request, id):   
    template_name = "annotator.html"
    data = Radiology2.objects.get(id=id)
    context = {"data": data}
    context["title"] = title
    context["version"] = version
    context["id"] = id

    if (request.is_ajax()):
        # return render(request, template_name, context)
        return JsonResponse(context)
    else:
        return render(request, template_name, context)

我添加了对 AJAX 的支持。我只是不确定在使用 AJAX 时如何正确地从视图中返回。显然,我不明白的东西。

标签: djangoajax

解决方案


而不是 Ajax,我替换window.location=url;$('#divIdToRefresh').load(url + ' #divIdToRefresh');


推荐阅读