javascript - MVC : Get JSON data from a controller using AJAX failed

标签 javascript jquery ajax asp.net-mvc

我正在尝试使用 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/

相关文章:

jquery - 在 Bootstrap X-editable 中添加加载程序图像/文本

javascript - 从 javascript 或 jquery 中的 htmlstring 查找宽度和高度

javascript - 从页面中删除行而不刷新页面

ajax - f :ajax action method is not invoked

jquery - 使用 MySql/Node js 创建通知服务器

javascript - 如何检测滚动值是否大于窗口高度?

php - 在jquery中为ajax调用创建循环

javascript - exportTableToCSV 的 JS 变量替换怎么做?

javascript - Vanilla Javascript 文本框数据绑定(bind),如 AngularJS

javascript - 将变量传递给 jquery .css() 函数