Jquery调用webservice

Jq调用webservice

 

Jq调用webservice在写法上和调用一般处理程序等方法略有不同

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class AjaxService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public User GetUser(int id,string name,string password)
        {
            User user = new User() { Id = id, UserName = name, Password = password };
            return user;
        }

        [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;
        }
    }
    [Serializable]
    public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

以上是服务端代码

客户端的代码如下:

function Button1_onclick() {

  $.ajax({
    type: "post",
    contentType: "application/json",
    url: "AjaxService.asmx/HelloWorld",
    data: {},
    dataType: "json",
    success: function (result) {
        alert(result.d);
    }
});

}

function Button2_onclick() {

  $.ajax({
    type: "post",
    contentType: "application/json",
    url: "AjaxService.asmx/GetUser",
    data: '{"id":1,"name":"张三","password":"123456"}',
    dataType: "json",
    success: function (result) {
        alert(result.d.UserName);
    }
});

}

function Button3_onclick() {

  $.ajax({
    type: "post",
    url: "Handler1.ashx",
    data: {"name":"张三","age":"22"},
    dataType: "json",
    success: function (result) {
    $(result).each(function() {
                        alert(this.name);
                    });
    }
});

}
function Button4_onclick() {

  $.ajax({
    type: "post",
    contentType: "application/json",
    url: "AjaxService.asmx/GetUserList",
    data: {},
    dataType: "json",
    success: function (result) {
        $.each(result.d,function(index,data){
        alert(data.UserName);
        });
    }
});

}

总结主要有以下这几点不同

1.需要说明 contentType: "application/json",而调用一般数理方法是这个属性是不需要加上的。

2. 数据传参时data: '{"id":1,"name":"张三","password":"123456"}',数据传参要写成这种形式,一般处理程序学成的形式是 data: {"name":"张三","age":"22"}

3.返回数据时

  success: function (result) {
        $.each(result.d,function(index,data){
        alert(data.UserName);
        });

注意其中的result.d,而一般处理程序我们处理返回的数据是直接$.each(result,function (i,item) {

另外就是注意的是 参数传递名称一定要和Service方法参数名称一致。

 

 

posted @ 2012-11-10 13:39  Andy_Wong  阅读(129)  评论(0编辑  收藏  举报