我有一个api控制器CustomerController
,它返回客户数据:
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 = "florianhofmeister@test.de",
company = "Germany",
pictureURL = "......jpg"
},
new Customer
{
Id = 2,
firstName = "Svenja",
lastName = "Hofmeister",
emailAddress = "svenjahofmeister@test.de",
company = "Germany",
pictureURL = "......jpg"
},
new Customer
{
Id = 3,
firstName = "Marvin",
lastName = "Hofmeister",
emailAddress = "marvinhofmeister@test.de",
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
。
答案 0 :(得分:1)
ajax中的url与任何控制器或操作都不匹配。如果脚本在cshtml文件中,您可以使用url helper来构建url。出于安全原因,如果您在此进行身份验证,我建议使用POST而不是GET。最后,您可以使用responseText查看实际的错误消息。
$.ajax({
url: @Url.Action("Customers", "GetAllCustomers"), // or try 'http://localhost:54172/Customers/GetAllCustomers'
type: 'POST',
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.responseText + '\n' + y + '\n' + z + "TEST");
console.log(x.responseText + '\n' + y + '\n' + z + "TEST");
}
});
答案 1 :(得分:0)
尝试将网址更改为此网址 - &gt; ControllerName /方法
答案 2 :(得分:0)
在我看来你应该明显改变ajax(/ controller / action)中的url并从你的api控制器返回json。因此,我不会在您的代码中看到名为客户的操作。
答案 3 :(得分:0)
API没有任何问题,我怀疑在尝试创建customer
集合时,你的JavaScript正在爆炸。尝试将其添加到JavaScript:
function customer(id, firstname, lastname, companyname, email, pic) {
this.Id = id;
this.FirstName = firstname;
this.LastName = lastname;
this.Company = companyname;
this.email = email;
this.Pic = pic;
}
并且更改您正在创建的变量,我已在示例中更改为cus
...
var cus = new customer(
'1',
data[i].id,
data[i].firstName,
data[i].lastname,
data[i].companyName,
data[i].emailAddress,
data[i].pictureURL);
self.customers.push(cus);