2.返回对象类型
代码如下:
[WebMethod]
public User GetUser()
{
User user = new User() { Id = 1, UserName = "zhang san", Password = "123qwe" };
return user;
}
$.ajax({
type: "post",
contentType: "application/json",
url: "UserService.asmx/GetUser",
data: "{}",
dataType: "json",
success: function (result) {
alert(result.d.Id + " " + result.d.UserName);
}
});
3.返回泛型集合类型
代码如下:
[WebMethod]
public List<User> GetUserList()
{
List<User> list = new List<User>()
{
new User{Id=1,UserName="zhang san",Password="asfasdf"},
new User{Id=2,UserName="li si",Password="3rwer"},
new User{Id=3,UserName="wang wu",Password="rqwe"}
};
return list;
}
$.ajax({
type: "post",
contentType: "application/json",
url: "UserService.asmx/GetUserList",
data: "{}",
dataType: "json",
success: function (result) {
$.each(result.d, function (index, data) {
alert(data.Id+" "+data.UserName);
});
}
});
对于泛型集合,对应的相应正文为:{"d":[{"__type":"WebServiceDemo.User","Id":1,"UserName":"zhang san","Password":"asfasdf"},{"__type":"WebServiceDemo.User","Id":2,"UserName":"li si","Password":"3rwer"},{"__type":"WebServiceDemo.User","Id":3,"UserName":"wang wu","Password":"rqwe"}]}。这时,result.d得到的是一个数组,通过each方法来遍历数组的每一项的属性值。
4.传递参数。在传递参数的时候,需要注意的是,ajax请求的参数的名称必须和WebService中的方法的名称一致,否则调用不能成功。
代码如下:
[WebMethod]
public string Hello(string name)
{
return "Hello " + name;
}
$.ajax({
type: "post",
contentType: "application/json",
url: "UserService.asmx/Hello",
data: "{name:'admin'}",
dataType: "json",
success: function (result) {
alert(result.d);
}
});