Ajax下载图像模板

时间:2015-11-01 16:41:49

标签: 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: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')    

1 个答案:

答案 0 :(得分:0)

这个代码的问题是什么?这个动作的问题是什么?..

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

  • 向您的查看功能发出ajax请求(此处:帖子)
  • 获取图片的路径(显然你很好)
  • 返回功能返回模板的路径
  • this question on StackOverFlow
  • 中显示图片

实施例:     

    $('#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>