在不刷新页面的情况下更新页面上的数据

43
我有一个网站需要更新状态,比如乘坐航班、出发、巡航或降落等。我希望在不用让浏览者重新加载整个页面的情况下刷新状态。我知道可以使用AJAX和jQuery来实现,但我对此一无所知。同时,我也不希望他们需要点击按钮。如果有人知道该怎么做,请告诉我,非常感谢!

3
你好,欢迎来到 SO。它不像 elancer.com 那样工作,所以你需要先找到一些代码,然后提出具体问题。 - mplungjan
4个回答

50
这通常是通过一种称为AJAX(即"异步JavaScript和XML")的技术实现的。该技术以异步方式(在后台)加载数据(使用XML格式),因此可以在不重新加载页面的情况下更新内容(使用JavaScript)。
实现AJAX最简单的方法是使用jQuery load()方法。该方法提供了一种简单的方式,可以从Web服务器异步加载数据,并将返回的HTML放入所选元素中。该方法的基本语法是:$(selector).load(url, data, complete); 其中参数为:
- selector:要加载数据的现有HTML元素 - url:包含发送请求的URL的字符串 - data(可选):与请求一起发送到服务器的普通对象或字符串 - complete(可选):请求完成时执行的回调函数
所需的URL参数指定要加载的文件的URL。 可选的数据参数允许您指定与请求一起发送到Web服务器的数据(即键/值对)。可选的complete参数可用于引用回调函数。每个选定元素都会触发一次回调。
一个可视化:

visualization

使用 load() 的简单示例,当按下按钮时动态加载数据:

使用 jQuery

$(function() {

  // optional: don't cache ajax to force the content to be fresh
  $.ajaxSetup({
    cache: false
  });

  // specify the server/url you want to load data from
  var url = "https://baconipsum.com/api/?type=meat-and-filler";

  // on click, load the data dynamically into the #demo div
  // while loading, show three dots (…)
  $("#button").click(function() {
    $("#demo").html("…").load(url);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>
  <div id="demo">
    <h1>Use jQuery load() to change this text</h1>
    <button id="button" type="button">Change Content</button>
  </div>
</body>

</html>

如果您不想使用jQuery库,也可以使用纯JavaScript。以这种方式加载内容会稍微复杂一些。以下是仅使用JavaScript的示例:

使用纯JavaScript

function loadContent(url) {
  const xhttp = new XMLHttpRequest();
  xhttp.open("GET", url);
  xhttp.send();
  xhttp.onreadystatechange = (e) => {
    document.getElementById("demo").innerHTML = xhttp.responseText;
  }
}
<!DOCTYPE html>
<html>

<body>
  <div id="demo">
    <h1>Use a XMLHttpRequest to change this text</h1>
    <button type="button" onclick="loadContent('https://baconipsum.com/api/?type=meat-and-filler')">Change Content</button>
  </div>
</body>

</html>

要了解有关AJAX的更多信息,您可以查看https://www.w3schools.com/xml/ajax_intro.asp


3
嗨!谢谢你的建议!但是在你的例子中,我还需要点击一个按钮,有没有办法在不点击任何东西的情况下更新数据呢? - Gidimotje
1
@gidimotje 是的,在这种情况下,您可以只删除 click() 部分,代码将直接运行。您还可以使用简单的 setTimeout() 语句在 x 秒后加载内容。 - Jean-Paul

14

假设您想在网页上显示一些实时内容(例如livefeed.txt),而不需要任何页面刷新,则以下简化示例适用于您。

在下面的HTML文件中实时数据会更新到id为"liveData"

元素中。

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Live Update</title>
    <meta charset="UTF-8">
    <script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
    <p>Loading Data...</p>
</div>
</body>
</html>

以下是autoUpdate.js,它使用XMLHttpRequest对象读取实时数据,并在每1秒钟更新html div元素。我已经在大部分代码上添加了注释,以便更好地理解。

autoUpdate.js

window.addEventListener('load', function()
{
    var xhr = null;

    getXmlHttpRequestObject = function()
    {
        if(!xhr)
        {               
            // Create a new XMLHttpRequest object 
            xhr = new XMLHttpRequest();
        }
        return xhr;
    };

    updateLiveData = function()
    {
        var now = new Date();
        // Date string is appended as a query with live data 
        // for not to use the cached version 
        var url = 'livefeed.txt?' + now.getTime();
        xhr = getXmlHttpRequestObject();
        xhr.onreadystatechange = evenHandler;
        // asynchronous requests
        xhr.open("GET", url, true);
        // Send the request over the network
        xhr.send(null);
    };

    updateLiveData();

    function evenHandler()
    {
        // Check response is ready or not
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            dataDiv = document.getElementById('liveData');
            // Set current data text
            dataDiv.innerHTML = xhr.responseText;
            // Update the live data every 1 sec
            setTimeout(updateLiveData(), 1000);
        }
    }
});

为了测试目的:只需在livefeed.txt中写一些东西-您将在不刷新任何内容的情况下在index.html中获得更新。

livefeed.txt

Hello
World
blah..
blah..

注意:您需要在Web服务器(例如:http://localhost:1234/index.html)上运行上述代码,而不是作为客户端HTML文件(例如:file:///C:/index.html)。


setTimeout(updateLiveData, 1000); -> 在 updateLiveData 后面不应该有()。 - VioletPL

8
你可以在官方的jQuery网站上了解有关jQuery Ajax的信息: https://api.jquery.com/jQuery.ajax/ 如果你不想使用任何点击事件,那么你可以设置定时器来定期更新。
以下代码可能会为您提供帮助,仅供参考。
function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

每过10秒,该函数将调用response.php获取内容并在#some_div中更新。

1
这个链接可能会更有帮助:http://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html - Butani Vijay

1

如果你想了解ajax的工作原理,直接使用jQuery并不是一个好方法。我建议学习如何使用原生的方式向服务器发送ajax请求,可以查看一些关于XMLHttpRequest的内容:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");

xhr.onreadystatechange = function () {}; // do something here...
xhr.send();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接