用JQuery中的Ajax方法获取web service等后台程序中的方法

                用JQuery中的Ajax方法获取web service等后台程序中的方法

1、准备需要被前台html页面调用的web Service,这里我们就用ws来代替了,代码如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Threading;
using System.Xml;

namespace StudyJq.ws
{
    /// <summary>
    /// MyWebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
    [System.Web.Script.Services.ScriptService]
    public class MyWebService : System.Web.Services.WebService
    {
        //无参数传递返回字符串
        [WebMethod]
        public string HelloWorld()
        {
            Thread.Sleep(5000);
            return "Hello World";
        }

//有参传递,返回字符串
        [WebMethod]
        public string GetPersonInfo(string name,int age)
        {
            string returnValue = string.Format("您的名字叫:{0},您的年龄是:{1},谢谢!",name,age.ToString());
            return returnValue;
        }

//返回一个集合
        [WebMethod]
        public List<int> GetArray(int i)
        {
            List<int> list = new List<int>();
            while (i >= 0)
            {
                list.Add(i);
                i--;
            }

return list;
        }

//返回一个复杂的类型Person
        [WebMethod]
        public Person GetPerson(string name)
        {
            Person p = new Person {Name=name,Age=18,School="北京大学" };

return p;
        }

//返回一个DataSet对象(XML)并返回
        [WebMethod]
        //给返回DataSet传递参数的方法没搞出来,一直报错,有知道的请指教
        public DataSet GetDataSet()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.TableName = "MyTable";
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");
            dt.Columns.Add("Address");

//添加数据到dt中
            for (int i = 0; i < 3; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = i + 1;
                dr["Name"] = "张三" + i.ToString();
                dr["Age"] = 19 + i;
                dr["Address"] = "北京市朝阳区" + (i + 1).ToString();

dt.Rows.Add(dr);
            }

ds.Tables.Add(dt);
            return ds;
        }

//获取后台方法返回的XML格式的数据
        [WebMethod]
        public XmlDocument GetXml()
        {
            string xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Person><id>123</id><name>张三</name></Person>";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlStr);
            return doc ;
        }

//获取后台方法返回的Json格式的数据
        [WebMethod]
        public string GetJsonData()
        {
            //string strJson = "{\"Name\":\"李二\",\"Age\":\"99\"}";//单个
            string strJson = "[{\"Name\":\"李二\",\"Age\":\"99\"},{\"Name\":\"王小六\",\"Age\":\"46\"}]";//json数组对象
            return strJson;
        }
        //获取指定路径的Xml并返回
        [WebMethod]
        public XmlDocument ReadXml()
        {
            //获取文件的绝对路径
            string filePath = Server.MapPath("../xml/XmlTemp.xml");
            XmlDocument doc = new XmlDocument();
            doc.Load(filePath);
            return doc;
        }

}

//自定义一个简单的类
    public class Person
    {
        public string Name { get; set; }

public int Age { get; set; }

public string  School{get;set;}
    }
}

2、前台的HTML代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Ajax调用Web Service方法</title>
    <script src="js/jquery-1.9.0.min.js"></script>
    <style type="text/css">
        .hover     
        {
            cursor: pointer; /*小手*/
            background: #ffc; /*背景*/
        }
        .button     
        {
            width: 150px;
            float: left;
            text-align: center;
            margin: 10px;
            padding: 10px;
            border: 1px solid #888;
        }
        #dictionary     
        {
            text-align: center;
            font-size: 18px;
            clear: both;
            border-top: 3px solid #888;
        }
        #loading     
        {
            border: 1px #000 solid;
            background-color: #eee;
            padding: 20px;
            margin: 100px 0 0 200px;
            position: absolute;
            display:none;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            //获取后台方法返回的文本格式的字符串,无参数传递
            $("#btnGetTextNoParam").click(function () {
                $.ajax({
                    url: "../ws/MyWebService.asmx/HelloWorld",
                    type: "post",
                    dataType: "json",
                    data: "{}",
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        $("#divContent").html(data.d);
                    },
                    error: function (xmlHttpRequest, textStatus, errorMsg) {
                        alert(errorMsg);
                    }
                });
            });

//获取后台方法返回的文本格式的字符串,有参数参数传递
            $("#btnGetTextParam").click(function () {
                //"{\"name\":\"aaa\"}"
                //将json对象转换成json字符串对象
                var testData = JSON.stringify({"name":"张三","age":"24"});
                $.ajax({
                    url: "../ws/MyWebService.asmx/GetPersonInfo",
                    type: "post",
                    data: testData,
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        $("#divContent").html(data.d);
                    },
                    error: function (xmlHttpRequest, textStatus, errorInfo) {
                        alert(errorInfo);
                    }
                });
            });

//获取后台方法返回的集合格式的数据
            $("#btnGetList").click(function () {
                $.ajax({
                    url: "../ws/MyWebService.asmx/GetArray",
                    type: "post",
                    data: "{\"i\":\"10\"}",
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        //集合对象得到的data是一个集合,所以只能通过遍历的方式来访问集合中的每一个变量
                        var arr = new Array();
                        $(data.d).each(function () {
                            arr[arr.length] = this.toString();
                        });

$("#divContent").html("你从后台获取到的集合对象的数据是:"+arr.join(","));
                    },
                    error: function (xmlHttpRequest, textStatus, errorInfo) {
                        alert(errorInfo);
                    }
                });
            });

//获取后台方法返回复合类型的变量
            $("#btnGetClass").click(function () {
                var testData = JSON.stringify({"name":"李小明"});
                $.ajax({
                    url: "../ws/MyWebService.asmx/GetPerson",
                    type: "post",
                    data: testData,
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        //复合类型的遍历也需要用到each方法,来一个一个读取类型中的字段的值
                        $(data.d).each(function () {
                            $("#divContent").html("您读取的Person对象的人的名字是:"+this["Name"]+",年龄是:"+this["Age"]+",毕业学校是:"+this["School"]);
                        });
                    },
                    error: function (xmlHttpRequest, textStatus, errorInfo) {
                        alert(errorInfo);
                    }
                });
            });

//获取后台方法返回的DataSet格式的数据
            $("#btnGetDataSet").click(function () {
                var testData = JSON.stringify({ "name": "李小明" });
                $.ajax({
                    url: "../ws/MyWebService.asmx/GetDataSet",
                    type: "post",
                    data: "{}",
                    dataType: "xml",
                    contentType: "application/xml;charset=utf-8",
                    success: function (data) {
                        //DataSet返回的是一个XML的对象,所以要使用each方法进行遍历返回
                        try
                        {
                            $(data).find("MyTable").each(function () {
                                $("#divContent").append("你得到的对象的ID是:" + $(this).find("Id").text()
                                    + ",名字是:" + $(this).find("Name").text()
                                    +",年龄是:"+$(this).find("Age").text()+",家庭地址是:"+$(this).find("Address").text()+"</br>");
                            });
                        }catch(e)
                        {
                            alert("出错啦!"+e);
                        }
                      
                    },
                    error: function (xmlHttpRequest, textStatus, errorInfo) {
                        alert(errorInfo);
                    }
                });
            });

//获取后台方法返回的XML格式的数据
            $("#btnGetXml").click(function () {
                $.ajax({
                    url: "../ws/MyWebService.asmx/GetXml",
                    type: "post",
                    data: "{}",
                    dataType: "xml",
                    contentType: "application/xml;charset=utf-8",
                    success: function (data) {
                        //获取的到是xml格式的字符串,解析
                        $(data).find("Person").each(function () {
                            $("#divContent").append("您从后台获取到的Xml文档中Person对象的ID是:" + $(this).find("id").text()
                                +",名字是:"+$(this).find("name").text()+"</br>");
                        })
                    },
                    error: function (xmlHttpRequest, textStatus, errorInfo) {
                        alert(errorInfo);
                    }
                });
            });

//获取后台方法返回的Json格式的数据
            $("#btnGetJsonData").click(function () {
                $.ajax({
                    url: "../ws/MyWebService.asmx/GetJsonData",
                    type: "post",
                    data: "{}",
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        //将json字符串转换成json对象
                        var jsonObj = eval("(" + data.d + ")");//后台给的一个json数组
                        $(jsonObj).each(function (index, value) {
                            $("#divContent").append("从后台获取到的json对象的名字是:" + jsonObj[index].Name
                                + ",年龄是:" + jsonObj[index].Age);
                        });
                    },
                    error: function (xmlHttpRequest, textStatus, errorInfo) {
                        alert(errorInfo);
                    }
                });
            });

//获取后台方法返回的读取的XML文件的数据
            $("#btnGetXmlFile").click(function () {
                $.ajax({
                    url: "../ws/MyWebService.asmx/ReadXml",
                    type: "post",
                    data: "{}",
                    dataType: "xml",
                    contentType: "application/xml;charset=utf-8",
                    success: function (data) {
                        //获取的到是xml格式的字符串,解析
                        $(data).find("Config").each(function () {
                            //得到的是一个Person对象数组
                            var $person = $(this).find("Person");
                            $person.each(function (index, value) {
                                //通过js的相关属性来获取属性的值
                                var domPerson = $person.get(index);//获取Dom对象
                                $("#divContent").append("您从后台读取到Config的Person配置的ID是:"
                                    + domPerson.getAttribute("Id") + ",名字是:" + domPerson.getAttribute("Name")
                                    + ",年龄是:" + domPerson.getAttribute("Age")+"</br>");
                            });
                        })
                    },
                    error: function (xmlHttpRequest, textStatus, errorInfo) {
                        alert(errorInfo);
                    }
                });
            });

//Ajax方法为用户提供反馈,加载遮罩层之类的
            $("#loading").ajaxStart(function () {
                $(this).show();
            }).ajaxStop(function () {
                $(this).hide();
            });
            //加载按钮的移入移除事件
            $("input[type=button]").hover(function () {
                $(this).addClass("hover");
            }, function () {
                $(this).removeClass("hover");
            })
        });
    </script>
</head>
<body>
    <input type="button" id="btnGetTextNoParam" value="获取后台方法返回的文本格式的字符串,无参数传递" /><br />
    <input type="button" id="btnGetTextParam" value="获取后台方法返回的文本格式的字符串,有参数参数传递" /><br />
   <input type="button" id="btnGetList" value="获取后台方法返回的集合格式的数据" /><br />
    <input type="button" id="btnGetClass" value="获取后台方法返回复合类型的变量" /><br />
    <input type="button" id="btnGetDataSet" value="获取后台方法返回的DataSet(XML)格式的数据" /><br />
    <input type="button" id="btnGetXml" value="获取后台方法返回的XML格式的数据" /><br />
    <input type="button" id="btnGetJsonData" value="获取后台方法返回的Json格式的数据" /><br />
    <input type="button" id="btnGetXmlFile" value="获取后台方法返回的读取的XML文件的数据" /><br />
     <div id="loading" style="display:none;">
         服务器处理中,请稍后。
     </div>

<div id="divContent" style="background-color:yellow;border:1px solid #f00">

</div>

</body>
</html>

3、用到的读取xml文件的文件是:

<?xml version="1.0" encoding="utf-8" ?>
<Config>
  <Person Id="9527" Name="张三" Age="19">我是一个测试的人1</Person>
  <Person Id="5345" Name="李四" Age="39">我是一个测试的人2</Person>
  <Person Id="1234" Name="王二麻子" Age="45">我是一个测试的人3</Person>
</Config>

以上是直接贴代码,仅供初学者使用,哈哈,我也菜鸟一个,相互学些

上一篇:Alink 1.1.1 在易用性上有哪些优化?


下一篇:Android中ListView实现图文并列并且自定义分割线(完善仿微信APP)