jQuery中调用WebService方法小结
1.返回字符串类型
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
$.ajax({
type: "post",
contentType: "application/json",
url: "UserService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function (result) {
alert(result.d);
}
});
[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);
}
});
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。