简体   繁体   English

使用ajax和jquery替换图像src

[英]replace image src using ajax and jquery

In my app, i have a web page with lots of images whose source url is generated dynamically by making get request to the rails server , initially a default image is assigned to the source. 在我的应用程序中,我有一个包含大量图像的网页,其图像的源URL是通过向Rails服务器发出get请求而动态生成的,最初是将默认图像分配给源。 After loading the page i make request to the server that return a json with new image URl, and then need to update the src of that image. 加载页面后,我向服务器请求,该服务器返回带有新图像URl的json,然后需要更新该图像的src。 Following is the code i am using in html.erb 以下是我在html.erb中使用的代码

<div class="inner">
 <div class="span9 blog-head alert alert-info"><h3><%=@feeds.title%></h3></div>
 <%@feeds.entries.each do|feed|%>
  <div class="thumbnail feeds span6">
   <div class="row title lead">
     <span class="span6"><%=link_to feed.title,feed.url,target: "_blank"%></span>
   </div>
   <div class="row content">
     <input type="hidden" class="image-feed-url" value="<%=feed.entry_id%>">
     <!-- need to update src of following img tag -->
     <img class="span2 desc-img thumbnail" src="/assets/default.jpg" alt="RSS">
     <span class="span3"><%=feed.summary%></span>
   </div>
   <div class="row footer">
     <%if feed.published%>
      <span class="span3">Published on: <small><%=feed.published.to_date.strftime("%b, %-d, %Y")%></span></small>
     <%end%>
     <span class="span2 source">Source: <small><%=link_to 'Click here',@feeds.url, target: "_blank"%></span></small>
   </div>
 </div>
 <%end%>
</div>

Need to update src in "img" tag having class "desc-img". 需要更新具有类“ desc-img”的“ img”标签中的src。 In my JS file 在我的JS文件中

$(document).ready(function(){
  all_feeds = $('.inner .feeds')
  for(i=0;i<all_feeds.length;i++)
  {
    element = all_feeds[i]
    feed_url = $(element).find('.image-feed-url').val()
    $.getJSON("/get_image_url?feed_url="+feed_url,function(data){
      // data['link] is the actual image link returned by server
      $(element).find('.desc-img').attr('src',data['link']);
    });
  }
});

I had also tried using div with background image instead of img tag and updating background image of div in JS but nothing works. 我也尝试过使用div和背景图片代替img标签,并在JS中更新div的背景图片,但是没有任何效果。 I am new to Jquery and Ajax, any help will be appreciated. 我是Jquery和Ajax的新手,将不胜感激。

try this : 尝试这个 :

$.getJSON("/get_image_url?feed_url="+feed_url,function(data){
      $(element).find('.desc-img').removeAttr('src');
      $(element).find('.desc-img').attr('src', '../' + data['link'] + '?' + Math.random());
});

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM