如何用ajax每分钟刷新一次页面?

问题描述

我想每 15 秒在我的页面上用比赛的分钟更新一个 div。我怎样才能做到这一点 ?我只想刷新那个 div 所在的区域。

  <script>
                        setInterval(function () {
                            $.ajax({
                                @*url: '@Url.Action("_List","Home",new { match_id=Model.match.match_id})',*@
                                cache: false,success: function (result) {
                                    $("#test").html(result);
                                    console.log(result)
                                    //alert(result);
                                }
                            });
                        },20000);
    </script>

解决方法

为此使用部分视图。它们将允许您仅更新 DOM 的一部分,而无需执行整个页面刷新或回发,并且它们是强类型的。

例如我在局部视图下面创建了

    function loadPartialView() {
   $.ajax({
    url: "@Url.Action("ActionName","ControllerName")",type: 'GET',// <-- make a async request by GET
    dataType: 'html',// <-- to expect an html response
    success: function(result) {
                $('#YourDiv').html(result);
             }
   });
}

$(function() {

   loadPartialView(); // first time

   // re-call the function each 5 seconds
   window.setInterval("loadPartialView()",5000);

});

每 5 秒后,它会转到控制器并执行操作

public class ControllerName: Controller
{
    public ActionResult ActionName()
    {
        .
        .   // code for update object
        .
        return PartialView("PartialViewName",updatedObject);
    }
}

了解更多信息 https://cmatskas.com/update-an-mvc-partial-view-with-ajax/