我正在学习Web api,我已经在其中创建了html页面,并且希望在我的html页面中获得<ul>
列表。
要调用api,我已经使用Jquery ajax调用了,但是似乎不起作用。我调试了Jquery,但没有收到错误。
请建议我我要去哪里了。
我的html代码
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
var listitem = $('#ulEmployees');
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
dataType: JSON,
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});
$('#btnClear').click(function () {
listitem.empty();
});
});
</script>
</head>
<body>
<input id="btn" value="Get All Employees" type="button" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees"></ul>
</body>
</html>
Web api GET
方法
public class EmployeesController : ApiController
{
public HttpResponseMessage Get(string gender="All")
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
switch(gender.ToLower())
{
case "all":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.ToList());
case "male":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "male").ToList());
case "female":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "female").ToList());
default:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not found");
}
}
}
}
答案 0 :(得分:0)
不应传递数据类型。您的函数应如下所示,数据类型为JSON。在jquery内部,尝试使用.toLower函数转换数据类型时,调用将失败。
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});