我是WebAPI的新手,我从一个简单的项目开始,我在模型中放了一些登录信息,这是我的控制器
public class UserAccountController : ApiController
{
UserAccounts[] userAccounts = new UserAccounts[]
{
new UserAccounts { Id = 1, FirstName = "Sam", LastName = "J", Email = "Sam@gmail.com", Password="s" },
new UserAccounts { Id = 2, FirstName = "Jack", LastName = "S", Email = "Jack@gmail.com", Password="j" },
new UserAccounts { Id = 3, FirstName = "Mark", LastName = "M", Email = "Mark@gmail.com", Password="m" },
};
public IEnumerable<UserAccounts> GetAllUserAccounts()
{
return userAccounts;
}
public IHttpActionResult GetUserAccount(int id)
{
var userAccount = userAccounts.FirstOrDefault((p) => p.Id == id);
if (userAccount == null)
{
return NotFound();
}
return Ok(userAccount);
}
}
}
我在同一个项目(webapi)中添加了一个HTML页面并编写了一个JQuery来检索记录,但我没有看到任何结果或错误。我如何调试或知道它是否正在打我的服务。我在做什么错?请帮忙
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:56546/api/UserAccount",
type: "Get",
success: function (data) {
for (var i = 0; i < data.length; i++) {
$(
Response.Write(data[i].FirstName)
)
}
},
error: function (msg) { alert(msg); }
});
});
</script>
答案 0 :(得分:0)
问题似乎与成功回调中的for循环有关:</ p>
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
在JavaScript中没有定义Response.Write,你会想要使用console.log这样的东西:
guess_one = int(raw_input("Guess a number from one to ten"))
对于服务器端,如果您使用的是Visual Studio,则还可以始终运行调试器并在API方法上设置断点以查看它们是否受到攻击。
答案 1 :(得分:0)
看起来您正在使用Getting Started with ASP.NET Web API 2教程中的简单项目。但是,你的jquery略有不同。如果您更改jquery以匹配其代码会发生什么:
$(document).ready(function () {
// Send an AJAX request
$.getJSON("http://localhost:56546/api/UserAccount")
.done(function (data) {
// On success, 'data' contains a list of user accounts.
$.each(data, function (key, item) {
// Add a list item for the user.
$('<li>', { text: item.FirstName }).appendTo($('body')); // changed this line to append to body since I don't know your markup
});
})
.fail(function(data) {
alert(data);
});
});