Ci sono almeno tre modi per farlo.
puro HTML
Come sottolineato da Amitd 's commento, in "show.html" aggiungere il seguente tag <meta>
all'elemento del documento <head>
:
<meta http-equiv="refresh" content="5" />
Questo si aggiorna automaticamente il pagina ogni 5 secondi. Regolare il valore dell'attributo content
sul numero desiderato di secondi.
Pure JavaScript:
Come sottolineato da MeNoMore, document.location.reload()
sarà aggiornare la pagina quando si chiama esso.
<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>
E come ha sottolineato tpower richieste AJAX potrebbe essere utilizzato, ma avresti bisogno di scrivere un servizio Web per restituire un URL per l'immagine desiderata.La JavaScript per fare una richiesta AJAX sarebbe simile a questa:
<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>
Altri metodi:
Infine, per rispondere alla tua domanda a cui rispondere tpower s' ... $.ajax()
sta usando jQuery per fare il Chiamata AJAX. jQuery è una libreria JavaScript che rende le chiamate AJAX e la manipolazione DOM molto più semplici. Per utilizzare la libreria jQuery, avresti bisogno di includere un riferimento ad esso nel vostro <head>
elemento (versione 1.4.2 utilizzato come esempio):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
Si potrebbe anche scaricare il "jquery.min.js" e lo ospitano localmente, ma questo, ovviamente, cambierà solo l'URL da cui è stato caricato lo script.
La funzione AJAX sopra, quando scritto usando jQuery sarebbe più simile a questo:
<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>
Come spero sia evidente, la versione jQuery è molto più semplice e più pulito. Tuttavia, dato il piccolo scopo del tuo progetto, non so se vorresti preoccuparti del sovraccarico di jQuery (non che sia così tanto). Né so se i requisiti del tuo progetto permetteranno la possibilità di jQuery. Ho incluso questo esempio semplicemente per rispondere alla tua domanda su cosa fosse $.ajax()
.
Sono altrettanto sicuro che esistono altri metodi con cui è possibile eseguire l'aggiornamento dell'immagine. Personalmente, se l'URL dell'immagine è in continua evoluzione, utilizzerei la rotta AJAX. Se l'URL dell'immagine è statico, probabilmente utilizzerò il tag di aggiornamento <meta>
.
Ma si sta già dicendo la browser quando per aggiornare l'immagine src (ogni 5 secondi). In quale evento vuoi aggiornarlo? – devnull69
Intendevi che più utenti stanno caricando immagini e ogni utente deve visualizzare sempre l'ultima immagine? – enenen
c'è anche il meta tag http://www.webmonkey.com/2010/02/refresh_a_page_using_meta_tags/ – Amitd