我有一个API控制器CustomerController
返回客户的数据:JQuery的Ajax调用ASP.NET MVC API返回错误
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using CustomerMngmt.Models;
namespace CustomerMngmt.Controllers
{
public class CustomersController : ApiController
{
private readonly Customer[] _customer =
{
new Customer
{
Id = 1,
firstName = "Florian",
lastName = "Hofmeister",
emailAddress = "[email protected]",
company = "Germany",
pictureURL = "......jpg"
},
new Customer
{
Id = 2,
firstName = "Svenja",
lastName = "Hofmeister",
emailAddress = "[email protected]",
company = "Germany",
pictureURL = "......jpg"
},
new Customer
{
Id = 3,
firstName = "Marvin",
lastName = "Hofmeister",
emailAddress = "[email protected]",
company = "Germany",
pictureURL = "......jpg"
}
};
public IEnumerable<Customer> GetAllCustomers()
{
return _customer;
}
public Customer GetCustomerById(int id)
{
var customer = _customer.FirstOrDefault(c => c.Id == id);
return customer;
}
}
}
然后我在JavaScript加载数据有:
function loadCustomer() {
jQuery.support.cors = true;
$.ajax({
url: 'http://localhost:54172/api/customers',
type: 'GET',
dataType: 'json',
data:{},
success: function (data) {
for (var i = 0; i < data.length; i++) {
var customer = new customer(
'1',
data[i].id,
data[i].firstName,
data[i].lastname,
data[i].companyName,
data[i].emailAddress,
data[i].pictureURL);
self.customers.push(customer);
}
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z + "TEST");
console.log(x + '\n' + y + '\n' + z + "TEST");
}
});
}
和我问题在于该功能不会从控制器加载元素。相反,我收到一条错误消息[object Object]errorTEST
。
我看不出你的API有什么问题。尝试将'url'更改为'url:'/ api/customers''。 – Groyoh 2014-10-30 13:15:27
是你的API调用会好吗? – 2014-10-30 13:16:05
检查控制台中的网络选项卡以查看实际响应和错误。 – tymeJV 2014-10-30 13:16:58