[英]Appending html with a django link in ajax
I have an ajax function that adds data to my python database without refreshing the page (I'm using the django web framework). 我有一个ajax函数,可将数据添加到我的python数据库中,而无需刷新页面(我使用的是django网络框架)。 I return the data and add this to my template with a html append to avoid a page refresh.
我返回数据,并使用html追加将其添加到我的模板中,以避免刷新页面。
However, I want to link this newly appended data to the actual record it belongs to. 但是,我想将此新附加的数据链接到它所属的实际记录。 So when a user clicks the 'newly added row' they can go to the record view and add things to it.
因此,当用户单击“新添加的行”时,他们可以进入记录视图并向其中添加内容。 So this is where I have a problem... I can't just throw in a django link without getting errors... Here is my ajax:
所以这是我有问题的地方...我不能不加任何错误就抛出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
}
});
};
})
What I would want to do is something like this - even though it's hideous: 我想做的是这样的-即使这很可怕:
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>';
But I can't put a django link in... 但是我无法在其中添加Django链接...
Are there any workarounds to this? 有什么解决方法吗?
As suggested by @ExperimentsWithCode, I had to deliver s string of html with json. 正如@ExperimentsWithCode所建议的那样,我必须用json传递html字符串。 And I had to get the field id in the view and insert it into the url as follows:
而且我必须在视图中获取字段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)
So I create the link in the view. 因此,我在视图中创建了链接。 Then I alter the html append as follows:
然后我将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>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.