ajax jQuery更新页面,无需刷新 [英] ajax jquery update page without refreshing

查看:118
本文介绍了ajax jQuery更新页面,无需刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前拥有以下功能,该功能可在刷新页面时更新div中的数据,这可以正常工作,但是我想编辑该功能以使其每隔2秒不断更新一次,而不必刷新页面.我将如何去做?

I currently have the below function which updates the data in a div when the page is refreshed and this works fine however i want to edit the function to make it constantly update say every 2 seconds without having to refresh the page. How would i go about doing this?

<script>
    $(document).ready(function ajaxLoop() {
        //-----------------------------------------------------------------------
        // Send a http request with AJAX Jquery
        //-----------------------------------------------------------------------
        $.ajax({
            url: 'getOrderStatus.php', // Url of Php file to run sql         
            data: "",
            dataType: 'json', //data format      
            success: function ajaxLoop(data) //on reciept of reply
                {
                    var OrdersSubmitted = data[0].SUBMITTED; //get Orders Submitted Count
                    var OrdersFulfilled = data[0].FULFILLED; //get Orders Fulfilled count
                    //--------------------------------------------------------------------
                    // 3) Update html content
                    //--------------------------------------------------------------------
                    $('#OrdersSubmitted').html("SUBMITTED:" + OrdersSubmitted);
                    $('#OrdersFulfilled').html("FULFILLED:" + OrdersFulfilled); //Set output html divs
                }
        });
    });
</script>

推荐答案

您可以链接setTimeout调用以实现此目的:

You can chain setTimeout calls to achieve this:

$(document).ready(function() {
    function updateOrders() {
        $.ajax({                                      
            url: 'getOrderStatus.php',                                  
            dataType: 'json',
            success: function ajaxLoop(data) {
                var OrdersSubmitted = data[0].SUBMITTED;
                var OrdersFulfilled = data[0].FULFILLED;
                $('#OrdersSubmitted').html("SUBMITTED:"+ OrdersSubmitted);
                $('#OrdersFulfilled').html("FULFILLED:"+ OrdersFulfilled);

                setTimeout(updateOrders, 2000);
            } 
        });
    });

替代方法是setInterval(),但是,如果请求变慢,则可能导致调用排队,最终导致内存问题.

The alternative is setInterval(), however if the requests slow down this can lead to calls being queued, which will eventually lead to memory issues.

这篇关于ajax jQuery更新页面,无需刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆