首页 > 解决方案 > 如何在 MVC 5 中使用 jQuery AJAX 和 setInterval 加载 div?

问题描述

我正在使用 jQuery Ajax。我想每 5 秒加载一次我的表的数据。这是我尝试过的,但它不起作用。它不返回任何错误或结果。

public ActionResult Index()
{
  return View();
}

public PartialViewResult _List()
{
  List<Purchase> model = db.Purchases.ToList();
  return PartialView("_List", model);
}
<div id="loadList"></div>

@section scripts{
  <script>
    $(document).ready(function () {
      setInterval(function () {
        $("#loadList").load("~/Views/Purchases/_List.cshtml");
      }, 3000);
    });
  </script>
}

我要加载的部分视图#loadList div

@model IEnumerable<ChocolateFactory.Data.Purchase>

<table class="table">
<tr>
    <th>@Html.DisplayNameFor(model => model.RefNo)</th>
    <th>@Html.DisplayNameFor(model => model.Date)</th>
    <th>@Html.DisplayNameFor(model => model.Amount)</th>
</tr>
@foreach (var item in Model) {
<tr>
    <td>@Html.DisplayFor(modelItem => item.RefNo)</td>
    <td>@Html.DisplayFor(modelItem => item.Date)</td>
    <td>@Html.DisplayFor(modelItem => item.Amount)</td>
</tr>
}
</table>

部分视图位于:

~/Views/Purchases/_List.cshtml

标签: c#jqueryasp.net-mvchtmlasp.net-mvc-partialview

解决方案


问题是因为波浪字符是站点根目录的 Razor 构造。在此之外它无法识别,因此它在您的 JS 代码中不起作用。当您将此逻辑放置在视图中时,您可以@Url.Content()在将 URL 输出到 JS 之前使用它来解析 URL:

setInterval(function () {
  $("#loadList").load("@Url.Content("~/Views/Purchases/_List.cshtml")");
}, 3000);

另请注意,如果您的路由配置正确,那么您可以使用Url.Action()更健壮的,例如@Url.Action("_List", "ControllerNameHere");

但是,应该注意的是,每 3 秒向您的服务器发出一个 AJAX 请求并不是一个好主意。它根本无法扩展,并且会导致性能问题。如果您需要保持服务数据和客户端 UI 密切同步,那么使用服务器发送事件或 WebSockets 会更好。


推荐阅读