【问题标题】:In MVC - Ajax call on page load is failing [duplicate]在 MVC 中 - 页面加载时的 Ajax 调用失败 [重复]
【发布时间】:2016-06-13 23:28:54
【问题描述】:

我在页面加载时进行 ajax 调用。它的失败。

我的ajax请求是

  @{
        ViewBag.Title = "Home Page";
    }

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    var token = $('input[name="__RequestVerificationToken"]').val();
    $.ajax({
        headers: {
            '__RequestVerificationToken': token
        },
        url: "Home/Test",
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        //data: JSON.stringify({ "ABC": "test" }),
        success: function (results) {
            //alert(url);
            alert("Success");
        },

        error: function (e) {
            alert(token);
            //alert("Fail");
        }
    });
});

HomeController 测试动作方法是

       [HttpPost]
    //[ValidateAntiForgeryToken]
    public JsonResult Test()
    {
        return new JsonResult();
    }

【问题讨论】:

  • 如果在控制器上设置断点,是否命中了Test方法?
  • 什么是 HTTP 错误?
  • @jwatts1980 是的,它正在测试方法
  • @AllenKing 控制台上没有 HTTP 错误
  • 您能告诉我们返回的错误是什么吗?你有error: function (e),但你什么都没告诉我们e

标签: jquery ajax asp.net-mvc asp.net-mvc-5


【解决方案1】:

您需要进行以下更改:

  1. 更改传递参数的方式

示例:

  $(document).ready(function () {

        var data = { "ABC": "test" };

        $.ajax({
            url: "@Url.Action("Test")",
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            success: function (results) {
                //alert(url);
                alert("Success");
            },

            error: function (e) {
                alert("Fail");
            }
        });
    });
  1. 在 HomeController 中像这样更改 Test 方法。

示例:

[HttpPost]
public JsonResult Test(string ABC)
{
    return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多