jquery - 使用 ajax 更新数据库后重新加载页面
问题描述
所以我需要在使用 ajax 请求向控制器发送数据后重新加载我的页面。控制器将其保存到数据库中,然后重新加载的页面应该具有更新的内容:
[控制器]
public class ProcessingController : Controller
{
ManageProcessing runManager = new ManageProcessing();
[Authorize]
public ActionResult Index()
{
RunModel rm = new RunModel
{
RunList = runManager.GetRunModelList()
};
return View(rm);
}
[HttpPost]
public ActionResult SaveReprocessData(Run runPost)
{
runManager.SaveToDataBase(runPost);
return RedirectToAction("Index", "Processing");
}
}
[看法]
function Reprocess() {
var checkedID = '#' + document.querySelector('input[name="select"]:checked').value;
var line = $(checkedID)[0].children;
var obj = {};
obj.ID = line[0].textContent;
obj.EndDate = line[1].textContent;
obj.ProcessedDate = line[2].textContent;
$.ajax({
type: "POST",
url: '@Url.Action("SaveReprocessData", "Processing")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
dataType: "json",
success: function (result) {
window.location.reload();
alert("updated licenses");
},
error: function (ex) {
alert(ex);
console.log("we have failed");
}
});
}
SaveReprocessData 应该返回什么来接收视图上的新视图?以及如何使用该回报?
解决方案
我同意托比亚斯。您通过尝试重新加载页面来破坏使用 ajax 的全部目的,但您的解决方案将只是更改SaveReprocessData方法的返回类型并返回一个新的数据列表
[HttpPost]
public RunModel SaveReprocessData(Run runPost)
{
runManager.SaveToDataBase(runPost);
return runManager.GetRunModelList();
}
此外,除非在执行 ajax POST 请求后客户端需要在服务器端生成值,否则您可以避免对数据库的额外调用。您只需要将您的 javascript 代码更新为这样的内容
$.ajax({
type: "POST",
url: '@Url.Action("SaveReprocessData", "Processing")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
dataType: "json",
success: function (result) {
// window.location.reload();
// alert("updated licenses");
reloadView(obj);
},
error: function (ex) {
alert(ex);
console.log("we have failed");
}
});
推荐阅读
- mongodb - 如何将对象添加到mongodb中的数组
- python - TensorFlow 对 python 3.7.4 的支持
- python - MoviePy 不显示非英文字符
- java - 为什么我的包是空对象引用?
- python - 编写一个 Python 程序,请求一个单词(小写字母)作为输入并将该单词翻译成 Pig Latin
- php - 在教义中设置@JoinColumn 名称
- javascript - JQuery下拉单击功能在asp.net mvc中不起作用
- codeigniter - 如何在codeiginter中上传多张照片?
- node.js - Windows 10 无法再通过 node.js 运行 javascript 文件或显示版本或 npm
- c# - 如何确定自定义线程池的#threads?