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

标签 javascript html ajax browser page-refresh

我有三台电脑; 服务器客户端查看器。我控制着服务器和查看器。 workflow

  1. Client 上的用户连接到 Server 并显示一个网页。
  2. 用户通过 php 脚本上传图像。
  3. 图像嵌入在一些 html 中。
  4. Viewer 是一台完全没有用户交互的计算机——没有键盘。 Viewer 始终运行 Web 浏览器,显示图片页面。

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

我知道 html、css、javascript、php 和 ajax,但显然还不够。

最佳答案

至少有三种方法可以做到这一点。

纯 HTML

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

<meta http-equiv="refresh" content="5" />

这将每 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>

正如 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>

其他方法:

最后,回答你的问题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>

您也可以下载“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>

正如我希望的那样,jQuery 版本更简单、更清晰。但是,鉴于您的项目范围较小,我不知道您是否愿意为 jQuery 的额外开销而烦恼(并不是那么多)。我也不知道您的项目要求是否允许使用 jQuery。我包括这个例子只是为了回答你的问题 $.ajax()是。

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

关于javascript - 如何以编程方式刷新浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13376048/

相关文章:

php - 分页面板应保持静态

javascript - 获取与父级相关的子级边距

html - 背景图像 url 响应图像

jquery - 显示区域的 CSS 滚动条

javascript - 通过ajax请求提交jQuery.each结果

javascript - jquery ajax方法请求体为空但postman工作正常

javascript - 为什么嵌入时指令之间的 Angular 绑定(bind)会中断?

php - 只能发布 2 分钟以内的 YouTube 视频

javascript - 关于 JavaScript 正则表达式的一种行为

html - 以 MYSQL 数据类型存储文章