我的应用程序目录中有图像。我想在我的模板中使用此图像。我使用Ajax请求获取图像的路径,我想在模板中显示图像。我怎么能这样做?我的代码:
def posts(request):
if request.is_ajax():
offset = request.GET.get('offset')
limit = request.GET.get('limit')
all_posts = Post.objects.all().order_by('-pub_date')[offset:limit]
if all_posts:
data = []
for obj in all_posts:
# image = PostImage.objects.filter(pk=obj.pk)
image = obj.postimage_set.all()
js = {
'info': 'success',
'id': obj.pk,
'title': obj.title,
'description': obj.description,
'pub_date': obj.pub_date.strftime("%d.%m.%Y %H:%M"),
}
if image:
img = {'image': str(image[0].image)}
else:
img = {'image': ''}
js.update(img)
data.append(js)
return HttpResponse(json.dumps(data), content_type='application/json; charset=utf8')
else:
return HttpResponse(404)
else:
return render(request, 'main.html')
答案 0 :(得分:0)
这个代码的问题是什么?这个动作的问题是什么?..
要使用Ajax导入模板中的图像,您需要:
实施例:
$('#list li a').click(function () {
var url = $(this).attr('href'), //Replace with ajax call to your function
image = new Image();
image.src = url;
image.onload = function () {
$('#image-holder').empty().append(image); //Replace id
};
image.onerror = function () {
$('#image-holder').empty().html('That image is not available.'); //Replace id
}
$('#image-holder').empty().html('Loading...'); //Replace id
return false;
});
</pre>