2012-11-14 195 views
27

我有三台电脑; Server,ClientViewer。我在控制服务器和查看器。 workflow如何以编程方式刷新浏览器

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

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

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

+1

但你已经当刷新图像SRC(每5秒)告诉浏览器。您想在哪个事件中刷新它? – devnull69

+0

您的意思是说多个用户上传图片,每个用户每次都必须查看最新的图片? – enenen

+4

还有meta标签 http://www.webmonkey.com/2010/02/refresh_a_page_using_meta_tags/ – Amitd

回答

43

至少有三种方法可以实现这一点。

纯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返回所需的图像。JavaScript的做一个AJAX请求将是这个样子:

<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路线。如果图片网址是静态的,我可能会使用<meta>刷新标记。

+0

对OP开放的各种选择有很好的回顾,很好的工作可以让其他人感兴趣,特别是考虑到_not_不仅仅是将jQuery用于其众多功能之一因为这确实是过度杀伤的, –

3

使用。

document.location.reload(); 

例如,为了应对点击一个按钮:

<input type="button" value="Reload Page" onClick="window.location.reload()"> 
+0

如何调用该函数? – hpekristiansen

+0

对不起,我忘了说我需要从客户端做到这一点。 - 看我的编辑。 – hpekristiansen

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"> 

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

+0

好的 - 我会研究AJAX。如果服务器被告知要刷新,那将更加优雅。通过上传php脚本。 – hpekristiansen

+0

1+ ..另请参阅websockets的此示例http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/ – Amitd

+0

即使浏览器位于同一台计算机上, web开发的角度来看,你仍然需要像其他客户端页面一样编写页面。除非你想告诉浏览器外部刷新,这可能是非常棘手的,这取决于你的浏览器和操作系统。 – tpower

1

您需要实现客户端与服务器的长轮询连接,称为COMET,或者如果您的浏览器支持websocket,请使用套接字。

1

在JavaScript中,有几种方法可以以编程方式进行刷新。

的首选方法是location.reload()

另一种方式是通过设置location.href属性,浏览器会自动转到新的URL,因此location=locationlocation.href=location.href也将这样做。

虽然第二种方法可能看起来很奇怪。

总括来说,这就是:

location.reload(); 
//or 
location.href=location.href; 
//or 
location=location; 


我希望这有助于。

5

在特定的时间间隔重新加载页面可能会有所斩获。

setTimeout(function(){ 
window.location.reload(1); 
}, 5000); 

上述代码在5秒内重新载入当前页面。

OR

你也可以去一个Ajax调用,这将是assynchronous,你也不会有刷新整个页面。结帐下面的代码:

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

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

[**的test.html:**此页面有可能带来的负荷中的所有图片src进去即服务将图像带入页面。]

在执行此操作时,您将在done(function()中获得data的结果,您可以将该结果指定给当前页面中的html元素。例如:

done(function() { 
$('#ImageId').attr('src', data); 
}); 

这将设置img标签来data的SRC从Test.aspx的

优势:整个页面不会被刷新,并添加只有新形象。

去深入这个link了解更多关于jQuery的阿贾克斯...

17

我有相同的应用程序。只需使用WebSockets即可。

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

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


详情:

是否需要像pywebsocketphpwebsocket一个WebSocket的服务器。

客户:

将需要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); 
} 

每当服务器发送一个更新,映射到wSocket.onmessage该函数将被调用,你可以做任何你需要做的事。

服务器:

将监听来自客户端的连接(可向支持多个客户端)。一旦建立连接并收到消息"sendImageUpdates",服务器将等待图像中的任何更新。当新图像上传时,服务器将创建一条新消息并发送给客户端。作为图像上传,只有当 图像上传

优点

  1. 会尽快得到更新。
  2. 客户都知道,像发生了变化,可以做更多的 功能。
  3. 完全异步和服务器驱动。
+2

网络套接字是一种方式,你甚至不需要刷新页面,只需更新你想要更新的内容,它完全是异步的,并且是服务器驱动的。查看器,您可以确定查看器是否支持此操作。 – Leeish

+0

我正在建议websockets,但已经指出某人已经做了。这是websockets的完美场景。有了所有可能的图像,页面重新加载将花费太长时间。服务器会一遍又一遍地轮询投票。添加离线功能,您的观众是一个不错的应用程序。 –

+0

赢得网络套接字。相比之下,轮询方法效率低下。 –

1

最简单的方法是使用AJAX池。
对于在PHP文件交给上传,当一个新的照片被上传保存在一个文件中的unix时间戳:

file_put_contents('lastupload.txt', strval(time())); // Save timestamp of upload 

创建另一个PHP文件(例如:polling.php)将处理AJAX调用和返回最后上传的UNIX时间戳:

echo file_get_contents('lastupload.txt'); // Send last upload timestamp 

在浏览器需要的时候JavaScript代码进行AJAX投票,将检测的时间戳的变化和刷新图像:

$(function() { 
    setInterval(polling, 1000); // Call polling every second. 
}); 
var lastupload = 0; 
function polling() { 
    $.ajax({ 
     url: 'polling.php', 
     success: function(timestamp){ 
      if (timestamp > lastupload) { // Is timestamp newer? 
       document.images['image'].src = 'image.png?' + timestamp; // Refresh image 
       lastupload = timestamp; 
      } 
     } 
    }); 
} 

我没有测试代码,所以可能会有错误,但这是主意。

1

我不认为你需要大量的脚本了点。我解决了这个问题,只是在图片url之后添加一个问号和随机数。如果您不更改图像url浏览器从缓存中调用它。

要在页面上显示最新的PIC:

<img src="<?php echo $image_url; ?>?<?php echo rand(10,99); ?>"/> 

它打印出像:

http://static.example.com/myimage.jpg?56 

你的问题,我的解决方案是通过使用jQuery随机数改变它刷新的图像网址和JavaScript的随机数字功能在我的问题。我认为你已经明白了,并且会适应你的需要。

$('#crop_image').live('click',function(){ 
    $(this).html(ajax_load_fb); 
    var x = $('#x').val(); 
    var y = $('#y').val(); 
    var w = $('#w').val(); 
    var h = $('#h').val(); 
    var dataString = 'process=image_crop&x='+x+'&y='+y+'&w='+w+'&h='+h; 
    $.ajax({ 
     type: 'POST', 
     url: '<?php echo $siteMain;?>ajax/ajaxupload.php', 
     data: dataString, 
     cache: false, 
     success: function(msg) { 
      $('#crop_image').html('Crop Selection'); 
      $('.crop_success_msg').slideDown('slow'); 
      var numRand = Math.floor(Math.random()*101); 
      $('#current_img').html('<img src="/images/large_<?php echo $user['username'];?>.jpg?'+numRand+'"/>'); 
     }, 
     error: function(response, status, error) 
     { 
      $(this).html('Try Again'); 
     } 
    }); 
}); 
0

最好的解决方案是在浏览器网页浏览器上写一个小的php脚本来定期检查图像,如果它改变了它将重新加载它。 由于php代码在服务器端运行,因此您可以轻松完成。 我希望这有助于如果你需要代码片段让我知道。