简体   繁体   English

更新页面上的数据而不刷新

[英]Update data on a page without refreshing

I have a website where I need to update a status.我有一个需要更新状态的网站。 Like for a flight, you are departing, cruise or landed.就像飞行一样,您正在起飞、巡航或降落。 I want to be able to refresh the status without having my viewers to have and reload the whole page.我希望能够在不让我的观众拥有并重新加载整个页面的情况下刷新状态。 I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works.我知道有一种方法可以使用 AJAX 和 jQuery,但我不知道它是如何工作的。 I also don't want them to have and click a button.我也不希望他们拥有并单击按钮。 If anybody knows how that would be done I much appreciate it!如果有人知道如何做到这一点,我将不胜感激!

In general, if you don't know how something works, look for an example which you can learn from.一般来说,如果您不知道某些东西是如何工作的,请寻找可以从中学习的示例。

For this problem, consider this DEMO对于这个问题,考虑这个DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:你可以看到使用 AJAX 加载内容很容易用 jQuery 完成:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it.尝试了解这是如何工作的,然后尝试复制它。 Good luck.祝你好运。

You can find the corresponding tutorial HERE你可以在这里找到相应的教程

Update更新

Right now the following event starts the ajax load function:现在以下事件启动 ajax load功能:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?您也可以定期执行此操作: 如何定期触发 AJAX 请求?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE .我在此处为您制作了此实现的演示。 In this demo, every 2 seconds ( setTimeout(worker, 2000); ) the content is updated.在这个演示中,每 2 秒( setTimeout(worker, 2000); )更新一次内容。

You can also just load the data immediately:您也可以立即加载数据:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.其中有这个相应的演示。

Suppose you want to display some live feed content (say livefeed.txt ) on you web page without any page refresh then the following simplified example is for you.假设您想在没有任何页面刷新的情况下在您的网页上显示一些实时提要内容(比如livefeed.txt ),那么以下简化示例适合您。

In the below html file , the live data gets updated on the div element of id "liveData"在下面的html 文件中实时数据在 id “liveData”div元素上更新

index.html索引.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>

Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second.下面的autoUpdate.js使用XMLHttpRequest对象读取实时数据并每 1 秒更新一次html div元素。 I have given comments on most part of the code for better understanding.为了更好地理解,我对大部分代码给出了注释。

autoUpdate.js自动更新.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);
        }
    }
});

For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.出于测试目的:只需在 livefeed.txt 中写一些东西 - 您将在 index.html 中获得相同的更新,无需任何刷新。

livefeed.txt livefeed.txt

Hello
World
blah..
blah..

Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).注意:您需要在Web 服务器上运行上述代码(例如:http://localhost:1234/index.html),而不是作为客户端 html 文件(例如:file:///C:/index.html)。

You can read about jQuery Ajax from official jQuery Site: https://api.jquery.com/jQuery.ajax/您可以从官方 jQuery 站点了解 jQuery Ajax: https : //api.jquery.com/jQuery.ajax/

If you don't want to use any click event then you can set timer for periodically update.如果您不想使用任何点击事件,那么您可以设置定时器进行定期更新。

Below code may be help you just example.下面的代码可能只是帮助你的例子。

function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

Above function will call after every 10 seconds and get content from response.php and update in #some_div .上述函数将每 10 秒调用一次,并从 response.php 获取内容并在#some_div更新。

I think you would like to learn ajax first, try this: Ajax Tutorial我想你想先学习ajax ,试试这个: Ajax教程

If you want to know how ajax works, it is not a good way to use jQuery directly.如果你想知道ajax是如何工作的,直接使用jQuery并不是一个好方法。 I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest :我支持学习向服务器发送 ajax 请求的本机方式,请参阅有关XMLHttpRequest

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

xhr.onreadystatechange = handler; // do something here...
xhr.send();

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

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