我正在尝试使用 AJAX 从 Controller 查询数据,我的 Controller 是:
[HttpGet]
public ActionResult GetTestStatus(string userName)
{
var db = new SREvalEntities();
var allTests = db.Tests
.Where(x => string.Equals(x.Owner, userName))
.Select(x => new { CreateDate = x.CreateDate, EndDate = x.EndDate, Status = x.Status })
.OrderByDescending(x => x.CreateDate)
.ToList();
return Json(allTests, JsonRequestBehavior.AllowGet);
}
我的外部文件中的 javascript 代码是:
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td><a href=\"\">Goto</a></td></tr>";
});
}
});
$("#ShowDetail").html(txt);
}
当我尝试调试这个函数时,代码永远不会执行到
$("#ShowDetail").html(txt);
我的页面永远不会改变。我怎样才能让它发挥作用?谢谢。
最佳答案
当您使用$.ajax()
时,它是异步的。因此,在从 API 返回值之前调用 $("#ShowDetail").html(txt)
。
您应该在每个 block 之后设置html()
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias.value }, //Use the value property here
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td><a href=\"\">Goto</a></td></tr>";
});
$("#ShowDetail").html(txt); //Move code to set text here
}
});
}
关于javascript - MVC : Get JSON data from a controller using AJAX failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36787903/