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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5987802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:46:12  来源:igfitidea点击:

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

phpjavascripthtmlajax

提问by algorithmicCoder

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、原型等。 编辑二:不知道为什么人们说 div 没有改变......其中的内容是动态的,它被抓取(比如从网络上抓取的)......每次它去抓取东西时,这些东西在源头上都发生了变化......一个例子可能是从 twitter 抓取搜索结果,它变化非常快......

采纳答案by trusktr

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

是的,您确实需要 Ajax,因为根据定义,这就是 Ajax。特别是如果您想从另一个网站获取内容。

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/

我知道你说你想使用普通的 javascript,但看看这个,也许你会喜欢这个。看看这个很棒的 jQuery 插件。 https://github.com/jamespadolsey/jQuery-Plugins/tree/master/cross-domain-ajax/

It VERY SIMPLE TO USEit let's you perform Ajax sing jQuery with one VERY BIG DIFFERENCE: you can grab content from ANYWHERE(e.g. 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!

很简单,用它让你有一个非常大的不同执行Ajax星jQuery的:你可以抓住从内容上任何地方(例如,在其他网站上的内容来自)。您只需像在您自己的服务器上一样使用相同的 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.

这将从something.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 秒)重复 function(){} 中的任何内容。

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-pageinto #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. 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 simplemethod i just explained a try.

总而言之,这是一种加载内容的超级简单方法。jQuery 只有 31kb(缩小),我相信这是值得的。当 jQuery 可以做你想做的事情时,没有必要重新发明轮子,而且效率很高,除非你正在努力学习 javascript。如果您只想让您的网站正常工作(最终结果才是最重要的),那么请尝试使用我刚刚解释的超级简单方法。

回答by joelhardi

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.

好的,所以您确实需要 AJAX。好吧,不是“X”部分,您只需要异步 Javascript 部分。服务器可以返回 XML 或 JSON,但在您的情况下,最简单的方法是返回您想要放入 div 的 HTML 块。

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 tutorialthat explains everything. I'll adapt it to what you want here.

这是一个30 秒的教程,解释了所有内容。我会根据你的需要调整它。

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.

首先,在服务器端,您已经有了一个 PHP 脚本,我们称之为“page.php”,它返回整个 HTML 页面。您将需要制作第二个 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. 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.

好的,现在,Javascript。如果您不想,您不必使用库——库的优点在于它们可以处理所有跨浏览器问题。

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);

回答by ace

You can make a recursive function that will change the content of your divthat 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.

您可以创建一个递归函数来更改您的内容,div使其看起来像是刷新了。就像一个计时器方法,每组时间都会改变时间。我不知道你将如何获得将加载到 上的数据,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. Before the refreshDiv()call again, change the value of you div.

您将看到 setTimeout 将再次调用时设置了一个时间,refreshDiv()因此这将类似于重新加载 div 的内容。在refreshDiv()再次调用之前,更改 you 的值div

回答by ace

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

看看jQuery.load()。请注意,reload从服务器获取信息。

回答by Peter Wilkinson

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. You'll want to replace the click trigger with a setInterval to constantly poll instead of triggering on demand.

简单的 ajax 请求演示展示了如何从 url 检索 html。您需要用 setInterval 替换点击触发器以不断轮询而不是按需触发。

回答by mozillanerd

Another way is to use "The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services"

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

回答by sitifensys

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.

希望这会有所帮助。