Вопрос

I have a Dashboard built in Ruby on Rails which fetches images from Webcams and serves them in jpg format.

I have a refresh button on each image and would like to be able to refresh each image individually without refreshing the whole page.

 <% @shares.each do |camera| %>
    <div class="col-md-4 col-sm-6 col-xs-12 cam-box">
        <a href="/cameras/<%= camera['id'] %>">
           <div id="cam-name"><h5><%= camera['name'] %></h5></div>
              <img src="<%= camera['jpg'] %>" alt="">
                <a href="#" id="cam-refresh" class="refresh"><span class="glyphicon glyphicon-refresh"></span></a>
           </div>
        </a>
    </div>
 <% end %>

Does anyone know how I might achieve this with Jquery?

Appreciate any suggestions.

Это было полезно?

Решение

Since you can just update the image without needing a new src url, you can do the following...

$("a.refresh").on("click", function(e) {
    e.stopPropagation();
    var $img = $(this).closest("img");
    var src = $img[0].src;
    src = src.substr(0, src.search("?")) + "?" + new Date().getTime();
    $img[0].src = src;
});

That will take the current image src and append a timestamp onto the end of it, causing a reload (rather than just use the same url and possible not load or load from the cache).

Also, you currently have it applying the same ID to all the refresh links. You should apply a unique ID to each of them (just append an incrementing value to each ID).

Finally, I added e.stopPropagation() so that the outer link does not react to you clicking the refresh link, otherwise the click would just bubble up and you'd end up changing the page.

Другие советы

What you want to do is to update the image asynchronously. You can do this using jQuery's .ajax()

Here's how you do it:

// Set up an onClick listener for the refresh button
// Make sure each refresh button has a class "cam-refresh"
$(".cam-refresh").click(function() { 
    var $img = $(this).closest("img"), // Find the closest image
        url = "filename.extension";    // The script that will return new image url

    // Make a request to that URL to obtain a new src parameter
    $.get(url, function() {
        alert('Request has been submitted');
    })
    .done(function(data) {
        alert( "second success" );
        $img.attr("src", data.src);
    })
    .fail(function() {
        alert( "error" );
    })
    .always(function() {
        alert( "finished" );
    });
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top