jQuery中调用WebService方法小结
在使用jQuery调用WebService的方法的时候,只能发送post方式的请求;如果要返回json格式的数据的话,需要将contentType设置为application/json;返回的数据是以字母d为键值的json对象。
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);
}
});
您可能感兴趣的文章:
c# WebService实例分享
jQuery中调用WebService方法小结
JavaScript调用WebService的实现方法
Jquery调用webService远程访问出错的解决方法
php怎么调用自建证书的webservice
jQuery dialog 异步调用ashx,webservice数据的代码
jQuery调用WebService的实现代码
Jquery调用Webservice传递Json数组
Jquery Ajax学习实例6 向WebService发出请求,返回DataSet(XML) 异步调用
Jquery Ajax学习实例3 向WebService发出请求,调用方法返回数据