使用JQUERY和AJAX自动刷新DIV内容

天我需要的内容在一个div至每5秒刷新 ,所以我决定做一个快速的演示向您展示如何是可以做到的。 它最初加载使用AJAX速记方法.load()的内容,然后简单地设置一个重复呼叫每5秒的数据。

JQUERY和AJAX调用代码

 (function($)
{
    $(document).ready(function()
    {
        $.ajaxSetup(
        {
            cache: false,
            beforeSend: function() {
                $('#content').hide();
                $('#loading').show();
            },
            complete: function() {
                $('#loading').hide();
                $('#content').show();
            },
            success: function() {
                $('#loading').hide();
                $('#content').show();
            }
        });
        var $container = $("#content");
        $container.load("rss-feed-data.php");
        var refreshId = setInterval(function()
        {
            $container.load('rss-feed-data.php');
        }, 9000);
    });
})(jQuery);

PHP数据脚本代码

 <?php
$feed_url = 'http://ilingku.com/blog/feed/';
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
$feedData = '';
$date = date("Y-m-d H:i:s");
 
//output
$feedData .=  "<ul>";
foreach($x->channel->item as $entry) {
    $feedData .= "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";
}
$feedData .= "";
$feedData .= "<p>Data current as at: ".$date."</p>";
 
echo $feedData;
?>

完整的案例代码

 <html>
<head>
<title>Auto Refresh Div Content Demo | jQuery4u</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
(function($)
{
    $(document).ready(function()
    {
        $.ajaxSetup(
        {
            cache: false,
            beforeSend: function() {
                $('#content').hide();
                $('#loading').show();
            },
            complete: function() {
                $('#loading').hide();
                $('#content').show();
            },
            success: function() {
                $('#loading').hide();
                $('#content').show();
            }
        });
        var $container = $("#content");
        $container.load("rss-feed-data.php");
        var refreshId = setInterval(function()
        {
            $container.load('rss-feed-data.php');
        }, 9000);
    });
})(jQuery);
</script>
</head>
<body>
 
<div id="wrapper">
    <div id="content"></div>
    <img src="loading.gif" id="loading" alt="loading" style="display:none;" />
</div>
 
</body>
</html>


发表评论 取消回复

很抱歉,您暂时无法发布评论。需要 登录 后才能发布。