[英]Ajax success event doesn't fire in Web Api 2
In my ASP.Net Web Api 2 application I'm using AJAX post to send registration form data to server when submit button was clicked. 在我的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');
}
});
}
And here is my Web Api Controller where I retund HttpStatusCode.OK if username doesn't exist, and HttpStatusCode.NotFound if username already exist. 这是我的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);
}
My controller every time return OK or NotFound but Ajax events success and error are never fired. 我的控制器每次返回OK或NotFound都不会触发Ajax事件成功和错误。
Does somebody know what is the problem? 有人知道是什么问题吗?
Most likely the List/Array of usernames
does not contains the posted value. usernames
列表/数组很可能不包含发布的值。 This will result in a 404 status code which is handle by the error callback in the ajax setup. 这将导致404状态代码,该代码由ajax设置中的错误回调处理。
But, in the error callback you have a typeo where alter()
should be alert()
and if you change that then most likely the error message will show. 但是,在错误回调中,您有一个typeo,其中alter()
应该是alert()
,如果您进行更改,则很可能会显示错误消息。
I found few problems - 我发现了几个问题-
type: 'POST'
instead of method: 'POST'
使用type: 'POST'
而不是method: 'POST'
dataType: 'json'
. 如果Action方法不返回任何内容,则不需要dataType: 'json'
。 Otherwise, error function will be called instead of success. 否则,错误函数将被调用而不是成功。 Fix: 固定:
<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>
If you use Web API 2, you can use Ok()
and NotFound()
, and return IHttpActionResult
. 如果使用Web API 2,则可以使用Ok()
和NotFound()
并返回IHttpActionResult
。 It is much cleaner and easy to read than old approach. 它比旧方法更干净,更易于阅读。
[HttpPost]
[Route("api/Account/registration")]
public IHttpActionResult Registration([FromBody] UserRegModel user)
{
if (!usernames[0].Contains(user.Username))
{
...
return Ok();
}
return NotFound();
}
FYI: I tested the above code, and it works fine. 仅供参考: 我测试了上面的代码,并且工作正常。 So, before you go through complex business logic, try to return Ok()
to make sure Ajax works. 因此,在经历复杂的业务逻辑之前,请尝试返回Ok()
以确保Ajax正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.