php 使用 AJAX / jQuery 刷新图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10920514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:21:46  来源:igfitidea点击:

Using AJAX / jQuery to refresh an image

phpjqueryhtmlajax

提问by dopey

This is probably a simple question but I am stumped and just don't know where to start.

这可能是一个简单的问题,但我很困惑,只是不知道从哪里开始。

I have a PHP script (image_feed.php) that returns a URL to an image. Every time this URl is called it returns the latest image available (the image changes every couple of seconds).

我有一个 PHP 脚本 (image_feed.php),它返回一个图像的 URL。每次调用此 URl 时,它都会返回可用的最新图像(图像每隔几秒更改一次)。

What I want to happen is that when the page loads, there is an AJAX call to image_feed.php, which returns the latest url. This URl is then inserted into the HTMl replacing the appropriate image src.

我想要发生的是,当页面加载时,有一个对 image_feed.php 的 AJAX 调用,它返回最新的 url。然后将该 URl 插入到 HTMl 中,替换适当的图像 src。

After 5 seconds, I want the process to repeat, and for the image to update. However, I don't want the image to be swapped until it has finished loading, and I want to avoid a white space appearing before the new image loads.

5 秒后,我希望重复该过程,并更新图像。但是,我不希望图像在加载完成之前被交换,并且我想避免在新图像加载之前出现空白。

At the moment I have the following jQuery, which simply loads the return value of image_feed.php directly into a div called #image1. image_feed.php is correctly formatted to provide a html image tag.

目前我有以下 jQuery,它只是将 image_feed.php 的返回值直接加载到名为 #image1 的 div 中。image_feed.php 格式正确以提供 html 图像标记。

    $(document).ready(function(){
    var $container = $("#image1");
    $container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>')
    var refreshId = setInterval(function()
    {
        $container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>');
    }, 5000);

}); 

This works, but there is a problem. I get a white space the size of the image in IE and Firefox every time the image refreshes, because the image takes a while to download.

这有效,但有一个问题。每次图像刷新时,我都会在 IE 和 Firefox 中获得与图像大小相同的空白区域,因为图像需要一段时间才能下载。

I know what I need to is for image_feed.php to return the plain URL to the image. I then use some jQuery to request this URL, pre-load it and then swap it with the existing image.

我知道我需要让 image_feed.php 返回图像的纯 URL。然后我使用一些 jQuery 来请求这个 URL,预加载它,然后将它与现有图像交换。

However, I'm still struggling to get anywhere. Could someone be so kind as to give me some pointers / help?

然而,我仍然在努力去任何地方。有人可以给我一些指示/帮助吗?

采纳答案by Finbarr

$(document).ready(function() {
    var $img = $('#image1');
    setInterval(function() {
        $.get('image_feed.php?CAMERA_URI=<?=$camera_uri;?>', function(data) {
            var $loader = $(document.createElement('img'));
            $loader.one('load', function() {
                $img.attr('src', $loader.attr('src'));
            });
            $loader.attr('src', data);
            if($loader.complete) {
                $loader.trigger('load');
            }
        });
    }, 5000);
});

Untested. Code above should load the new image in the background and then set the src attribute of the old image on load.

未经测试。上面的代码应该在后台加载新图像,然后在加载时设置旧图像的 src 属性。

The event handler for load will be executed only once. The .completecheck is necessary for browsers that may have cached the image to be loaded. In such cases, these browsers may or may not trigger the loadevent.

load 的事件处理程序将只执行一次。.complete对于可能已缓存要加载的图像的浏览器,该检查是必要的。在这种情况下,这些浏览器可能会也可能不会触发该load事件。

回答by Praveen Kumar Purushothaman

You can. When you want to reload something, you can just append a search query, so that it refreshes the source.

你可以。当您想重新加载某些内容时,您只需附加一个搜索查询,以便它刷新源。

For Eg., when there is a frequently changing image (say captcha) and you wanna load it again, without refreshing the browser, you can do this way:

例如,当有频繁更改的图像(例如验证码)并且您想再次加载它时,无需刷新浏览器,您可以这样做:

Initial Code:

初始代码:

<img src="captcha.png" alt="captcha" />

Refreshed Code:

更新后的代码:

<img src="captcha.png?1" alt="captcha" />

The script used here would be just:

这里使用的脚本只是:

var d = new Date();
$('img').attr('src', $('img').attr('src') + '?_=' + d.getMilliseconds());

Hope this helps! :)

希望这可以帮助!:)

回答by Praveen Kumar Purushothaman

Consider, if you have to fetch the URL again from the server, for a new image URL, you can do this way:

考虑一下,如果您必须再次从服务器获取 URL,对于新的图像 URL,您可以这样做:

$.ajax({
  url: 'getnewimageurl.php',
  success: function(data) {
    $('img').attr('src', data);
  }
});

The server should return only a new image name in it. For eg., the PHPcode should be this way:

服务器应该只返回一个新的图像名称。例如,PHP代码应该是这样的:

<?php
    $images = array("jifhdfg", "jklduou", "yuerkgh", "uirthjk", "xcjhrii");
    die($images[date('u') % count($images)] . ".png"); // Get the random milliseconds mod by length of images.
?>

回答by vivek.m

I suggest you use jQuery 'onImagesLoad' PluginThis provides you with a callback when an image has finished loading.

我建议您使用jQuery 'onImagesLoad' Plugin这会在图像加载完成时为您提供回调。

When you receive new image URL from server, you create a new <imgobject with src="new_url_from_server"and attach 'onImagesLoad'callback to it. When your callback is called, your image has finished downloading.

当您从服务器收到新的图像 URL 时,您创建一个新<img对象src="new_url_from_server"并将'onImagesLoad'回调附加到它。当您的回调被调用时,您的图像已完成下载。

Now you can just replace the 'src' attribute of old img object with new_url_from_server. Since new image is already avaiable in cache, it will not be downloaded again and will be immediately displayed!

现在你可以用 new_url_from_server 替换旧 img 对象的 'src' 属性。由于新图像已在缓存中可用,因此不会再次下载并立即显示!

Aletrnatively, you can hide the old image and add this new image to DOM (not required if above works correctly)

或者,您可以隐藏旧图像并将此新图像添加到 DOM(如果上述工作正常,则不需要)

Some bare bones sample could be like this:

一些裸骨样本可能是这样的:

<!DOCTYPE html> 
<html> 
<body> 
<img id='bla' src="10.jpg" />

<script type="text/javascript" src="jquery.min.js"></script> 
<script type="text/javascript" src="jquery.onImagesLoad.js"></script> 
<script type="text/javascript"> 
    $(function(){ 
        var img = $('<div><img src="http://myserverbla/images/verybig.jpg"></img></div>');
        img.onImagesLoad({ 
                all : allImgsLoaded 
            });

        function allImgsLoaded($selector){ 
            var allLoaded = ""; //build a string of all items within the selector 
            $selector.each(function(){ 
                $('#bla').attr('src','http://myserverbla/images/verybig.jpg');
            }) 
        } 
    }); 
</script> 

</body> 
</html>