我正在对提供身份验证例程的 Web API 服务进行简单的 ajax 调用。 我的问题是 ajax 调用可以向服务发出请求,但一旦服务返回 bool 值就会出错。
我想要什么:
我想做的就是检查返回的 bool 值是 true 还是 false。如果为真,我想将用户重定向到另一个页面。 有人可以帮我解决这个问题吗?
JQUERY 代码:
<script type="text/javascript">
$(document).ready(function () {
$('#submitButton').click(function () {
var name = $(userNameTextBox).val);
var pass = $(passwordTextBox).val();
if (name.length == 0 || pass.length == 0) {
alert("Please enter your credentials");
}
else {
$.ajax({
url: "http://localhost:50503/api/Authentication/Authenticate",
data: { userName: name, passWord: pass },
cache: false,
type: 'GET',
dataType: 'json',
success: function (msg) {
alert(msg);
},
error: function (msg) {
alert("Error Message: "+msg);
}
});
}//end of else
});
});
</script>
这是我的 webapi 服务
public class AuthenticationController : ApiController
{
[HttpGet]
[Route("api/Authentication/Authenticate")]
public bool Authenticate(string userName,string passWord)
{
if (userName.ToLower().Equals("username") && passWord.ToLower().Equals("password"))
{
return true;
}
else
{
return false;
}
}
}
最佳答案
您可以尝试用此替换您的ajax调用,删除dataType
:
var request = $.ajax({
url: "http://localhost:50503/api/Authentication/Authenticate",
cache: false,
type: 'POST',
data: { userName: userName, passWord: passWord }
});
request.done(function (msg) {
//check the boolean and redirect user to another page.
if(msg) window.location.href = "http://nextpage.com";
});
我还将方法更改为POST
。更适合您的情况。
关于javascript - Ajax 调用无法从 Web api 服务获取返回消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22115919/