Update DIV with Javascript

2

I have this code to update div every time, but I feel that it makes a lot of effort to my server.

<script language="Javascript" type="text/javascript">
function refreshDivs(divid,secs,url)
{

// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object

var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Tu explorador no soporta AJAX.");
return false;
}
}
}

// Timestamp para evitar que se cachee el array GET

fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}

var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;

// the ajax call
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}

// LLamamos las funciones con los repectivos parametros de los DIVs que queremos refrescar.
window.onload = function startrefresh(){
refreshDivs('div1',10,'ejemplo1.php');
refreshDivs('div2',10,'ejemplo2.php');
}
</script>
    
asked by Jhosselin Giménez 14.04.2017 в 23:53
source

1 answer

5

You can do it with Jquery. Something like this.

<script type="text/javascript">
    $(document).ready(function() {
        var refrescarid = setInterval(function() {
            $("#div1").load("url que quieres cargar")
            .error(function() { alert("Error"); });
        }, 1000); // Tiempo
        $.ajaxSetup({ cache: false });              
    });
</script>
    
answered by 15.04.2017 / 00:05
source