Ajax调用状态无法加载资源。 简单的asp.net联系人类

试着在这里学习一些jquery / js和一些ajax。 我创建了一个简单的asp.net Web表单项目,其中包含以下内容:

namespace JSONTest { public partial class _Default : System.Web.UI.Page { public class Contact { public string Name { get; set; } } List contacts = new List { new Contact{ Name = "George" }, new Contact{ Name = "Mike" }, new Contact{ Name = "Steve"} }; [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public List GetContacts() { return contacts; } } } 

我的js文件就是这样:

 $(document).ready(function () { $.ajax({ type: "POST", async: true, url: "Default.aspx/GetContacts", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $.each(data, function (key, val) { console.log(val.Name); }); } }); }); 

我希望javascript控制台显示联系人的名字,但它只是说Failed to load resource: The server responded with a status of 500 (internal server error) http://localhost:someNumber/Default.aspx/GetContacts 。 我不确定我做错了什么?

我的语法有点偏。 注意添加到web方法的static

 public partial class Default : System.Web.UI.Page { public class Contact { public string Name { get; set; } } static List contacts = new List { new Contact{ Name = "George" }, new Contact{ Name = "Mike" }, new Contact{ Name = "Steve"} }; [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static List GetContacts() { return contacts; } } 

服务器返回包装的JSON – 因此您需要使用data.d

 $(document).ready(function () { $.ajax({ type: "POST", async: true, url: "Default.aspx/GetContacts", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $.each(data.d, function (key, val) { console.log(val.Name); }); } }); }); 

另一种方法是使用ASMX服务而不仅仅是页面上的方法。 这使得方法不必是静态的,而且它是一个真正的Web服务。

 [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { public class Contact { public string Name { get; set; } } List contacts = new List { new Contact{ Name = "George" }, new Contact{ Name = "Mike" }, new Contact{ Name = "Steve"} }; [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public List GetContacts() { return contacts; } } 

和javascript:

 $(document).ready(function () { $.ajax({ type: "POST", async: true, url: "WebService1.asmx/GetContacts", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $.each(data.d, function (key, val) { console.log(val.Name); }); } }); });