简体   繁体   English

仅使用常规Javascript刷新页面中的一个<div>

[英]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? 如果我没有从服务器获取任何信息,但我想每N秒重新加载/刷新一次div,我该怎么做?

New to javascript: I've tried something like javascript新手:我尝试过类似的东西

 <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 我不清楚,如果我没有从服务器获取新信息,我需要AJAX ...所以现在我想知道如何让它在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... 编辑:我不喜欢使用库进行这个基本操作,所以理想情况下我不会使用jquery,原型等。编辑II:不知道为什么人们说div不变...它的内容是动态的,它被抓住了从网上说起来......并且每当它去抓东西的东西已经改变了......一个例子可能是抓住来自Twitter的搜索结果,变化非常迅速......

Yes you do need Ajax, because by definition, that is what Ajax is. 是的,你确实需要Ajax,因为根据定义,这就是Ajax。 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. 我知道你说你想使用普通的javascript,但看看这个,也许你会喜欢这个。 Take a look at this awesome jQuery plugin. 看看这个很棒的jQuery插件。 https://github.com/jamespadolsey/jQuery-Plugins/tree/master/cross-domain-ajax/ 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). 很简单,用它让你执行Ajax唱jQuery的一个很大的区别的:你可以抓住从任何地方的内容(如在其他网站上的内容来自)。 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! 你可以像在自己的服务器上一样使用相同的jQuery.load()方法或.ajax()方法,除了你可以从任何地方获取内容!

Just add the plugin script to the page (after jQuery), then use the .load() method as described here . 只需将插件脚本添加到页面(在jQuery之后),然后使用此处所述的.load()方法。

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. 这将从somewhere.com获得#newContent并将其放在您网站上的#target中。

You could do something like this using javascript's setInterval : 你可以使用javascript的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). 这将每5000毫秒(也称为5秒)重复函数(){}内的任何内容。

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 这将使#someContent和无论是在它的内部,从http://yoursite.com/some-page到#target上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. jQuery的大小只有31kb(缩小),我相信它是值得的。 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. 没有必要重新发明轮子,当jQuery可以做你想要的,并有效地,除非你试图进出javascript。 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. 您可以创建一个递归函数,它将更改div的内容,看起来它将被刷新。 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. 我不知道你将如何得到将加载到div上的数据,我假设你将处理这部分。

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. 你会看到setTimeout再次调用refreshDiv()时会设置一个时间,所以这就像重新加载div的内容一样。 Before the refreshDiv() call again, change the value of you div . 在再次调用refreshDiv()之前,更改div的值。

OK, so you do need AJAX. 好的,所以你确实需要AJAX。 Well, not the "X" part, you just need the asynchronous Javascript part. 好吧,不是“X”部分,你只需要异步Javascript部分。 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. 服务器可以返回XML或JSON,但在您的情况下,最简单的方法就是返回要放入div的HTML blob。

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. 这是一个30秒的教程 ,解释了一切。 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. 首先,在服务器端,你已经有了一个PHP脚本,我们称之为“page.php”,它返回整个HTML页面。 You will need to make a second PHP script, let's call it "div.php", that returns just the contents of the div. 你需要制作第二个PHP脚本,我们称之为“div.php”,它只返回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.) (你也可以让page.php查找一个参数,比如$ _GET ['divonly'],这样只有一个PHP脚本可以处理这两个作业。没关系......你可以随心所欲地做到这一点,只要您在服务器端有第二个URL来检索div的新内容。)

In the HTML of page.php, you've already got: 在page.php的HTML中,你已经有了:

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

And now you've added div.php, which returns only the " ... ", not a full HTML page. 现在你已经添加了div.php,它只返回“...”,而不是一个完整的HTML页面。

OK, so now, the Javascript. 好的,现在,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: 但这是你想要的,改编自纯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() . 看一下jQuery.load() Note that reload fetch info from the server. 请注意,从服务器reload提取信息。

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. 如果你热衷于自己做,以避免包含像jquery这样的完整库的开销,你可以看看这个。

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

The simple ajax request demo shows how to retrieve html from a url. 简单的ajax请求演示展示了如何从url中检索html。 You'll want to replace the click trigger with a setInterval to constantly poll instead of triggering on demand. 您将要使用setInterval替换单击触发器以不断轮询而不是按需触发。

另一种方法是使用“浏览器可以使用元数据(如何显示内容或重新加载页面),搜索引擎(关键字)或其他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);. 其次,如果按原样放置,由于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 作为侧节点,不建议使用此版本的setTimout函数,更好的方法是将函数作为第一个参数传递

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

Hope this will help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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