如何在特定div上显示ajax响应?这句话有效alert(data[i]['title']);
,但我希望在div上显示。感谢
<td><a onclick="ajax_request('{% url recommendation id=track.id %}');" href="#"> Click Here</a></td>
Ajax功能
function ajax_request(url) {
$.ajax({
url: url,
type: 'POST',
data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
success: function(data) {
for(i=0;i<=data.length;i++){
alert(data[i]['title']);
}
}
})
}
查看
@login_required
def recommendation(request, id):
if request.is_ajax() and request.method == 'POST':
track = Track.objects.get(pk=id)
recommend = Song.objects.filter(title__icontains=track.title)[:5]
results = []
for data in recommend:
results.append({'title': data.title})
json = simplejson.dumps(results)
return HttpResponse(json, mimetype="application/json")
答案 0 :(得分:0)
嗯,取决于你是否已经有一个div想要显示内容,或者你用jQuery创建一个新的:
现有ID为myDiv
的人:
$('#myDiv').html(data[i]['title']); //also $('#myDiv').text(data[i]['title']) possible
创建新div:
$('<div/>').html((data[i]['title']);
答案 1 :(得分:0)
您需要像这样修改onsuccess事件
$.ajax({
url: url,
type: 'POST',
data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
success: function(data) {
for(i=0;i<=data.length;i++)
$('#div').html(data[i]['title']);//Your success msg
}
});