c# - 如何在 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
解决方案
问题是因为波浪字符是站点根目录的 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 会更好。
推荐阅读
- laravel - git push 后cmd似乎坏了,如何修复clink.lua?
- datetime - Dart - 将时间从 dd/MM/YYYY 转换为 YYYY-MM-dd
- r - degree_distribution 向量间隔为 0 每隔一个数字
- oracle - 如何使 Oracle 查询排序顺序动态化?
- c++ - 如何强制 Windows.h 在 Visual Studio 中静态链接而不是动态链接?
- google-apps-script - Telegram Bot webhook 不适用于 Apps 脚本
- c - 为什么我不能在 POSIX 信号处理中使用 I/O?
- python - multiprocessing.Pool ==> TypeError:预期的字符串或 Unicode 对象,NoneType 找到
- java - 用于搜索特定关键字的正则表达式以及用于时间搜索的正则表达式
- laravel - hasOneThrough() 关系给出“BadMethodCallException,调用未定义方法 [模型名称]::hasOneThrough()”