简体   繁体   中英

Refreshing only one <div> in page with just regular Javascript

If I am not grabbing any information from the server but I want to reload/refresh a div every N seconds how do I do this?

New to javascript: I've tried something like

 <script type = 'text/javascript'>
    function refresh(){
        setTimeout(window.location.reload(), 10000);
    }

    </script>

    <div id='target' onLoad='refresh()'>
<?    
var =grab some rapidly changing content from the web    
print var
  ?>  
    </div>
    <div>
    some stuff that doesn't get refreshed
    </div>

Its not clear to me that I need AJAX if im not getting the new info from the server...so for now i'd like to know how to make it work just in javascript

EDIT: I prefer not to use a library for this basic operation so ideally I wouldn't use jquery, prototype etc. EDIT II: Not sure why people are saying the div isnt changing...the content in it is dynamic it is grabbed (say scraped) from the web...and everytime it goes to grab stuff the stuff has changed at the source...an example could be grabbing search results from twitter which change very rapidly...

Yes you do need Ajax, because by definition, that is what Ajax is. ESPECIALLY if you want to grab content from another website.

I know you said you want to use plain javascript, but check this out, maybe you'll like this. Take a look at this awesome jQuery plugin. https://github.com/jamespadolsey/jQuery-Plugins/tree/master/cross-domain-ajax/

It VERY SIMPLE TO USE it let's you perform Ajax sing jQuery with one VERY BIG DIFFERENCE: you can grab content from ANYWHERE (eg another website where your content comes from). You just use the same jQuery.load() method or .ajax() method just like you would on your own server, except you can grab content from anywhere!

Just add the plugin script to the page (after jQuery), then use the .load() method as described here .

So in your case, you can do something like this:

$('div#target').load('http://somewhere.com #newContent');

That will get #newContent from somewhere.com and place it inside #target on your site.

You could do something like this using javascript's setInterval :

setInterval( function() {
    $('div#target').load('http://somewhere.com #newContent');
}, 5000); //repeat function every 5000 milliseconds

That will repeat whatever is inside the function(){} every 5000 milliseconds (aka 5 seconds).

You can also get content from your own site:

$('div#target').load('http://yoursite.com/some-page #someContent');

That will put #someContent and whatever is inside of it from http://yoursite.com/some-page into #target on http://yoursite.com/whatever-the-current-page-is

All in all, this is a super simple way to load content. jQuery is only 31kb in size (minified), and I believe it's worth it. There's no need to reinvent the wheel when jQuery can do what you want, and efficiently at that, unless you are trying to learn javascript in and out. If you just want your site to work (the end result is what matters), then give the super simple method i just explained a try.

You can make a recursive function that will change the content of your div that will look like it is refreshed. Like a timer method, where every set of time will change the time. I don't know how will you get the data that will load on the div , with this I assume you will handle this part.

Here's the function

var gIndex = 1;
function refreshDiv(){
    document.getElementById('target').innerHTML = "Timer " + gIndex++;
    var refresher = setTimeout("refreshDiv()", 1000);
}

<body onLoad="refreshDiv()">
    <div>
        <span>HTML Content</span>
        <div id="target"></div>
    </div>
</body>

You will see that a time is set when setTimeout will call again the refreshDiv() so this will behave like reloading the content of the div. Before the refreshDiv() call again, change the value of you div .

OK, so you do need AJAX. Well, not the "X" part, you just need the asynchronous Javascript part. The server can return XML or JSON, but in your case it's simplest to have it just return the blob of HTML you want to put into the div.

But, you do have to make a roundtrip to the server, because nothing has changed in the browser, only the contents of the page on the server have changed.

Here's a 30-second tutorial that explains everything. I'll adapt it to what you want here.

First, on the server side, you already have a PHP script, let's call it "page.php", that returns this whole HTML page. You will need to make a second PHP script, let's call it "div.php", that returns just the contents of the div.

(You could also have page.php look for a parameter, like $_GET['divonly'], and that way have only one PHP script that handles both jobs. It doesn't matter ... you can do it however you want, just as long as you have a second URL to hit on the server side to retrieve the new content for the div.)

In the HTML of page.php, you've already got:

<div id="target"> ... </div>

And now you've added div.php, which returns only the " ... ", not a full HTML page.

OK, so now, the Javascript. You don't have to use a library if you don't want to -- what's nice about the libraries is that they take care of all of the cross-browser issues.

But here's what you want, adapted from the example in pure Javascript:

var refreshDelay = 10000;

/* Creates the XMLHTTPRequest object depending on the browser */
function createRequestObject() {
    var ro;
    if(navigator.appName == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}
var http = createRequestObject();

/* Makes the request back to /div.php ... change the URL to whatever
   script you put on the server side to return the contents of the div only */    
function sndReq() {
    http.open('get', '/div.php');
    http.onreadystatechange = handleResponse;
    http.send(null);
}

/* Does the work of replacing the contents of the div id="target" when
   the XMLHTTPRequest is received, and schedules next update */
function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        document.getElementById('target').innerHTML = response;
        setTimeout(sndReq(), refreshDelay);
    }
}

/* Schedules the first request back to the server. Subsequent refreshes 
   are scheduled in handleResponse() */
setTimeout(sndReq(), refreshDelay);

Take a look at jQuery.load() . Note that reload fetch info from the server.

If you're keen on doing it yourself to avoid the overhead of including a full library like jquery you can have a look at this.

http://www.dynamic-tools.net/toolbox/ajax/

The simple ajax request demo shows how to retrieve html from a url. You'll want to replace the click trigger with a setInterval to constantly poll instead of triggering on demand.

另一种方法是使用“浏览器可以使用元数据(如何显示内容或重新加载页面),搜索引擎(关键字)或其他Web服务”

Short answer :

1 . div 'onload' doesn't exist. So you need to register a listener for the page
    load event, or put it in "<body onload='refresh()'"
2 . function refresh(){
        setTimeout("window.location.reload()", 10000); // note the ""
    }

Long answer :

Your page doesn't refresh simply because you're function is never executed. Secondly if you put it as is, the page will get refreshed as soon as the page loads, because of setTimeout(window.location.reload(), 10000);.

As a side node, using this version of the setTimout function is not recommended, and a better approach is to pass the function as the first parameter

setTimeout(window.location.reload,1000); // we are passing the function,
                                         // not the function result    

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM