尝试在这里学习一些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<Contact> contacts = new List<Contact>
{
new Contact{ Name = "George" },
new Contact{ Name = "Mike" },
new Contact{ Name = "Steve"}
};
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Contact> 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 控制台显示联系人的姓名,但它只是说加载资源失败:服务器响应状态为 500(内部服务器错误)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<Contact> contacts = new List<Contact>
{
new Contact{ Name = "George" },
new Contact{ Name = "Mike" },
new Contact{ Name = "Steve"}
};
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Contact> 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<Contact> contacts = new List<Contact>
{
new Contact{ Name = "George" },
new Contact{ Name = "Mike" },
new Contact{ Name = "Steve"}
};
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Contact> 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);
});
}
});
});
