Jquery Ajax下载模板中的图像

Jquery Ajax下载模板中的图像,jquery,ajax,django,Jquery,Ajax,Django,我的应用程序目录中有图像。我想在模板中使用此图像。我使用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:l

我的应用程序目录中有图像。我想在模板中使用此图像。我使用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')    

这个代码有什么问题?这次行动有什么问题

要使用Ajax在模板中导入图像,您需要:

  • 向视图函数发出ajax请求(此处:posts)
  • 获取图像的路径(显然你对此没有意见)
  • 在返回函数的同时返回模板的路径
  • 显示如中所示的图像
例如: $('#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>
$(“#列出LIA”)。单击(函数(){ var url=$(this.attr('href'),//替换为对函数的ajax调用 图像=新图像(); image.src=url; image.onload=函数(){ $(“#图像持有者”).empty().append(图像);//替换id }; image.onerror=函数(){ $(“#图像持有者”).empty().html('该图像不可用');//替换id }

$('#图像持有者').empty().html('Loading…');//替换id
返回false;
});