【问题标题】:Ajax success event doesn't fire in Web Api 2Ajax 成功事件不会在 Web Api 2 中触发
【发布时间】:2017-09-07 17:41:09
【问题描述】:

在我的 ASP.Net Web Api 2 应用程序中,当单击提交按钮时,我使用 AJAX 发布将注册表单数据发送到服务器。

function click_form() {
var formData = JSON.stringify({
    Name: $('#regInputName').val(),
    SecondName: $('#regInputLastName').val(),
    Email: $('#regInputEmail').val(),
    Username: $('#regInputUsername').val(),
    Password: $('#regInputPassword').val(),
    Contact: $('#regInputContact').val(),
});

$.ajax({
    url: '/api/Account/registration',
    method: 'POST',
    data: formData,
    contentType: 'application/json;charset=utf-8',
    dataType: 'json',
    cache: false,
    success: function () {
        alert("Success");
    },
    error: function () {
        alter('Error');
    }
});
}

这是我的 Web Api 控制器,如果用户名不存在,我将返回 HttpStatusCode.OK,如果用户名已经存在,则返回 HttpStatusCode.NotFound。

[HttpPost]
[Route("api/Account/registration")]
    public HttpResponseMessage registration([FromBody] UserRegModel user)
    {            
        if (!usernames[0].Contains(user.Username))
        {
            User u = new User(){/*....*/}
            /*... updating database ... */

            HttpContext.Current.Session["user"] = u;        
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }

我的控制器每次都返回 OK 或 NotFound 但 Ajax 事件成功和错误永远不会被触发。

有人知道问题出在哪里吗?

【问题讨论】:

  • 您在错误处理程序中有错字 - alert 不是 alter
  • 你是对的,但这并不能解决我的问题。
  • 您在控制台中看到了什么?有什么错误吗?通话被屏蔽了吗?

标签: javascript jquery asp.net ajax asp.net-web-api2


【解决方案1】:

usernames 的列表/数组很可能不包含发布的值。 这将导致 404 状态代码,由 ajax 设置中的错误回调处理。

但是,在错误回调中,您有一个 typeo,其中 alter() 应该是 alert(),如果您更改它,那么很可能会显示错误消息。

【讨论】:

    【解决方案2】:

    我发现了一些问题 -

    • 使用type: 'POST' 而不是method: 'POST'
    • 如果 Action 方法没有返回任何东西,则不需要dataType: 'json'。否则,将调用错误函数而不是成功。

    修复:

    <button type="button" onclick="click_form()">Post Form via Ajax</button>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
        function click_form() {
            var formData = JSON.stringify({
                Name: 'John Doe',
                SecondName: 'Jonny',
                Email: 'johndoe@example.com',
                Username: 'johndoe',
                Password: '123456',
                Contact: 'Jannet Doe'
            });
    
            $.ajax({
                url: '/api/Account/registration',
                type: 'POST',
                data: formData,
                contentType: 'application/json;charset=utf-8',    
                cache: false,
                success: function (result) {
                    console.log(result);
                },
                error: function (result) {
                    console.log(result);
                }
            });
        }
    </script>
    

    如果你使用Web API 2,你可以使用Ok()NotFound(),并返回IHttpActionResult。它比旧方法更简洁易读。

    [HttpPost]
    [Route("api/Account/registration")]
    public IHttpActionResult Registration([FromBody] UserRegModel user)
    {
        if (!usernames[0].Contains(user.Username))
        {
            ...
            return Ok();
        }
        return NotFound();
    }
    

    仅供参考:我测试了上面的代码,它工作正常。因此,在处理复杂的业务逻辑之前,请尝试返回 Ok() 以确保 Ajax 正常工作。

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 1970-01-01
      • 2014-01-12
      • 2017-10-24
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多