jQuery 如何使用 AJAX 自动刷新 div 或网页
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27090263/
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
How to use AJAX for auto refresh a div or a web page
提问by gedamial
I've been trying to do this for a lot of time, but I can't. Here is my problem: I have a web page just like this:
我已经尝试这样做了很长时间,但我做不到。这是我的问题:我有一个像这样的网页:
<html>
<body>
<div id="my_div">
<span id="txt">HELLO WORLD</span>
</div>
</body>
</html>
Now I want that the div "my_div" refreshes itself every X seconds, also refreshing its content. How to do this using AJAX or JQUERY or JAVASCRIPT?
现在我希望 div "my_div" 每 X 秒刷新一次,同时刷新其内容。如何使用 AJAX 或 JQUERY 或 JAVASCRIPT 执行此操作?
Pay attention: I don't require a script that refreshes the entire page. Pay attention(2): I've just tried to find something by Google, but I found nothing.
注意:我不需要刷新整个页面的脚本。注意(2):我刚刚试图通过谷歌找到一些东西,但我什么也没找到。
Please, help me. I have been having this problem for many time.
请帮我。我已经遇到这个问题很多次了。
Thank you in advance!
先感谢您!
回答by charlietfl
Using jQuery load()
and an interval timer is about the simplest.
使用 jQueryload()
和间隔计时器是最简单的。
setInterval(function(){
$('#my_div').load('/path/to/server/source');
}, 2000) /* time in milliseconds (ie 2 seconds)*/
load()
is a shorthand method for $.ajax
load()
是一种简写方法 $.ajax
This assumes that you would set up a server side script that only outputs the content for that element.
You could also use a selector fragment within load
url to parse a full page for the specific content
这假设您将设置一个仅输出该元素内容的服务器端脚本。您还可以在load
url 中使用选择器片段来解析特定内容的完整页面
See load() API Docs
回答by Kenny Tai Huynh
you can write some stuff like
你可以写一些东西,比如
var doSth = function () {
var $md = $("#my_div");
// Do something here
};
setInterval(doSth, 1000);//1000 is miliseconds
回答by Kolban
Using jQuery, you can dynamically update the content of an element using:
使用 jQuery,您可以使用以下方法动态更新元素的内容:
$("#my_div").html("... new content ...");
The new content replaces the original content.
新内容取代了原来的内容。
Using the setInterval() method, you can cause JavaScript to be executed every period:
使用 setInterval() 方法,你可以让 JavaScript 在每个周期执行:
For example:
例如:
window.setInterval(function() {
$("#my_div").html("... new content ...");
}, 1000);
Would replace the content every second.
将每秒更换内容。