如何以编程方式刷新浏览器

hpe*_*sen 32 html javascript browser ajax page-refresh

我有三台电脑; Server,ClientViewer.我控制着服务器和查看器. 工作流程

  1. Client连接到Server和的用户会看到一个网页.
  2. 通过php脚本,用户上传图像.
  3. 图像嵌入在一些HTML中.
  4. Viewer是一台完全没有用户互动的电脑 - 没有键盘.将Viewer在运行Web浏览器,显示图片页面所有的时间永远是.

我现在的问题是,即使服务器磁盘上的图片发生变化,网页也不会更新.如何在查看器或部分网页上刷新Web浏览器?

我知道html,css,javascript,php和ajax,但显然不够好.

pet*_*ete 50

至少有三种方法可以实现这一目标.

纯HTML

正如Amitd的评论所指出的那样,在"show.html"中将以下<meta>标记添加到文档的<head>元素中:

<meta http-equiv="refresh" content="5" />
Run Code Online (Sandbox Code Playgroud)

这将每5秒自动刷新一次页面.将content属性的值调整为所需的秒数.

纯JavaScript:

正如MeNoMore所指出的,document.location.reload()当你调用它时会刷新页面.

<script type="text/javascript">
    //put this somewhere in "show.html"
    //using window onload event to run function
    //so function runs after all content has been loaded.
    //After refresh this entire script will run again.
    window.onload = function () {
        'use strict';
        var millisecondsBeforeRefresh = 5000; //Adjust time here
        window.setTimeout(function () {
            //refresh the entire document
            document.location.reload();
        }, millisecondsBeforeRefresh);
    };
</script>
Run Code Online (Sandbox Code Playgroud)

正如tpower指出的那样,可以使用AJAX请求,但是您需要编写一个Web服务来将URL返回到所需的图像.执行AJAX请求的JavaScript看起来像这样:

<script type="text/javascript">
    //put this somewhere in "show.html"
    //using window onload event to run function
    //so function runs after all content has been loaded.
    window.onload = function () {
        'use strict';
        var xhr,
            millisecondsBeforeNewImg = 5000;    // Adjust time here
        if (window.XMLHttpRequest) {
            // Mozilla, Safari, ...
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            // IE
            try {
                // try the newer ActiveXObject
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    // newer failed, try the older one
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // log error to browser console
                    console.log(e);
                }
            }
        }
        if (!xhr) {
            // log error to browser console
            console.log('Giving up :( Cannot create an XMLHTTP instance');
        }
        xhr.onreadystatechange = function () {
            var img;
            // process the server response
            if (xhr.readyState === 4) {
                // everything is good, the response is received
                if (xhr.status === 200) {
                    // perfect!
                    // assuming the responseText contains the new url to the image...
                    // get the img
                    img = document.getElementById('theImgId');
                    //set the new src
                    img.src = xhr.responseText;
                } else {
                    // there was a problem with the request,
                    // for example the response may contain a 404 (Not Found)
                    // or 500 (Internal Server Error) response code
                    console.log(xhr.status);
                }
            } else {
                // still not ready
                // could do something here, but it's not necessary
                // included strictly for example purposes
            }
        };
        // Using setInterval to run every X milliseconds
        window.setInterval(function () {
            xhr.open('GET', 'http://www.myDomain.com/someServiceToReturnURLtoDesiredImage', true);
            xhr.send(null);
        }, millisecondsBeforeNewImg)
    };
</script>
Run Code Online (Sandbox Code Playgroud)

其他方法:

最后,回答你的问题tpower的答案...... $.ajax()是使用jQuery来进行AJAX调用.jQuery是一个JavaScript库,它使AJAX调用和DOM操作变得更加简单.要使用jQuery库,您需要在<head>元素中包含对它的引用(以1.4.2版本为例):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

您也可以下载"jquery.min.js"并在本地托管它,但这当然只会更改您从中加载脚本的URL.

上面的AJAX函数,当使用jQuery编写时看起来更像是这样:

<script type="text/javascript">
    //put this somewhere in "show.html"
    //document.ready takes the place of window.onload
    $(document).ready(function () {
        'use strict';
        var millisecondsBeforeNewImg = 5000;    // Adjust time here
        window.setInterval(function () {
            $.ajax({
                "url": "http://www.myDomain.com/someServiceToReturnURLtoDesiredImage",
                "error": function (jqXHR, textStatus, errorThrown) {
                    // log error to browser console
                    console.log(textStatus + ': ' + errorThrown);
                },
                "success": function (data, textStatus, jqXHR) {
                    //get the img and assign the new src
                    $('#theImgId').attr('src', data);
                }
            });
        }, millisecondsBeforeNewImg);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

我希望很明显,jQuery版本更简单,更清晰.但是,考虑到你的项目范围很小,我不知道你是否想要担心jQuery的额外开销(不是那么多).我也不知道您的项目要求是否允许jQuery的可能性.我把这个例子简单地回答了你的问题$.ajax().

我同样确信还有其他方法可以用来刷新图像.就个人而言,如果图像网址总是在变化,我会使用AJAX路线.如果图片网址是静态的,我可能会使用<meta>刷新标记.


ATO*_*TOA 19

我有完全相同的应用程序.只是用WebSockets.

您可以启动a websocket connection,服务器会Viewer在收到更新时通知您.您可以通过websocket发送更新的图像,完全异步,而不会干扰显示或用户交互.

如果您使用计时器,您将无法获得快速更新,或者您将不使用时保持刷新页面.


细节:

将需要像pywebsocket或的Websocket服务器phpwebsocket.

客户:

将需要HTML5 websocket支持,所有当前浏览器都支持它.

需要在图像更新发生时注册消息.这就像注册一个回调.

例:

wSocket = new WebSocket('ws://' + serverIP + ':' + serverPort + '/images');

wSocket.onopen = function() {
    console.log("Primary Socket Connected.");

    connectedPrimary = true;

    wSocket.send("sendImageUpdates");
};

wSocket.onmessage = function(evt) {
    // evt is the message from server

    // image will be representated as a 64 encoded string

    // change image with new one
    $("#image").attr('src', 'data:image/png;base64,' + evt.data);
}

wSocket.onclose = function() {
    console.log("Primary Socket Closed.");

    wSocket = null;
};

wSocket.onerror = function(evt) {
    alert(evt);
}
Run Code Online (Sandbox Code Playgroud)

每当服务器发送更新时,将调用映射到的函数wSocket.onmessage,您可以执行任何操作.

服务器:

将侦听来自客户端的连接(可以支持多个客户端).建立连接并"sendImageUpdates"收到消息后,服务器将等待映像中的任何更新.上传新图像后,服务器将创建新消息并发送给客户端.

优点

  1. 只要上传图像,并且仅在上传图像时才会获得更新.
  2. 客户将知道图像已更改并可执行其他功能.
  3. 完全异步和服务器驱动.

  • Web套接字是要走的路.您甚至不必刷新页面,只需更新您想要更新的内容,它就像所指出的那样是完全异步和服务器驱动的.由于您控制了Viewer,因此可以确定Viewer是否支持此功能. (2认同)

tpo*_*wer 11

您可以使用AJAX请求来提供帮助.例如,您正在做的是每五秒钟对服务器轮询一次图像.相反,您可以轮询服务器以获取新的图像ID,并使用该ID而不是图像源的随机数.在这种情况下,src属性只会在有新图像时更改/重新加载.

<script language="JavaScript"><!--
function refreshIt() {
   if (!document.images) return;
   $.ajax({
      url: 'latest-image-id.json',
      success: function(newId){
          document.images['doc'].src = 'doc.png?' + newId;        
      }
   });
   setTimeout(refreshIt, 5000); // refresh every 5 secs
}
//--></script>
</head>
<body onLoad=" setTimeout(refreshIt, 5000)">
<img src="doc.png" name="doc">
Run Code Online (Sandbox Code Playgroud)

另一种方法是在图像通过Web套接字更改时从服务器获取通知.


小智 5

在特定时间间隔内重新加载页面可能会起到作用.

setTimeout(function(){
window.location.reload(1);
}, 5000);
Run Code Online (Sandbox Code Playgroud)

上面的代码在5秒内重新加载当前页面.

要么

您也可以进行ajax调用,它将是同步的,您也不必刷新整个页面.签出以下代码:

$.ajax({
  url: "test.aspx",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});
Run Code Online (Sandbox Code Playgroud)

这可以用于instaed window.location.reload(1);

[**test.html:**此页面必须将加载的所有图像src引入其中,即将图像引入页面的服务.

在这样做,你将得到的结果datadone(function(),你可以在当前页面assingn到HTML元素.例:

done(function() {
$('#ImageId').attr('src', data);
 });
Run Code Online (Sandbox Code Playgroud)

这会将img标记的src设置为datatest.aspx

优点:整个页面不会刷新,只添加新图像.

通过此链接了解有关jQuery Ajax的更多信息...