在 ajax 中使用 django 链接附加 html



我有一个ajax函数,可以在不刷新页面的情况下将数据添加到我的python数据库中(我使用的是django Web框架(。我返回数据并使用 html 追加将其添加到我的模板中,以避免页面刷新。

但是,我想将此新附加的数据链接到它所属的实际记录。因此,当用户单击"新添加的行"时,他们可以转到记录视图并向其中添加内容。所以这就是我有问题的地方...我不能只是扔一个 django 链接而不会出错......这是我的 ajax:

$( document ).ready(function()  {
$('#timesheet-form').on('submit', function(event){
    event.preventDefault();
    console.log("add a timesheet");
    createtimesheet();
});
function createtimesheet() {
    console.log("create timesheet is working!")
    $.ajax({
        url : "{% url 'tande:createtimesheet' %}",
        type: "POST",
        data: { datestart : $('#start').val(), dateend : $('#end').val()},
        success : function(json) {
            var html = '<tr><td>'+json.startdate+'</td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>';
            console.log("success"); 
            $('#timesheet-list').append(html);
        },
        error : function(xhr,errmsg,err) {
            // what to do when there is an error
            }
        });
    };
})

我想做的是这样的事情 - 即使它很可怕:

var html = '<tr><td><a href='{% url "tande:timesheet" timesheet_id=sheet.id %}' class="class2">'+json.startdate+'</a class="class2"></td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>';

但是我不能放一个姜戈链接...

有什么解决方法吗?

正如@ExperimentsWithCode所建议的,我必须用json提供html字符串。我必须在视图中获取字段 ID 并将其插入 url,如下所示:

def createtimesheet(request):
    print "create timesheet view"
    if request.method == "POST":
        #Get all the data and do stuff
        # now we can create the timesheet!
        peach = TimeSheet(start_date=start_date_formatted, end_date=end_date_formatted, person_id=person)
        peach.save()
        #json response data for the link
        response_data['linkstart'] = "<a href='/tande/"+str(peach.id)+"/person/timesheet/' class='class2'>"
        response_data['linkend'] = "</a class='class2'>"
        #other response data
        return JsonResponse(response_data)

所以我在视图中创建了链接。然后我更改 html 附加如下:

var html = '<tr><td>'+json.linkstart+json.startdate+json.linkend+'</td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>';

最新更新