2015-11-01 39 views
0

我在我的應用程序目錄中有圖像。我想在我的模板中使用這個圖像。我使用Ajax請求獲取圖像的路徑,我想在模板中顯示圖像。我怎麼能做到這一點?我的代碼:模板中的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

這是什麼問題與此代碼? ?什麼是這個動作的問題..

要使用Ajax模板導入圖像,您需要:

  • ,從AJAX請求您的視圖功能(這裏的帖子)
  • 讓您的圖片的路徑(所以顯然你行與)
  • 返回的路徑與您的函數的返回模板
  • 顯示圖像,你可以在this question on StackOverFlow
012看

示例:

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