用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>

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

用JQuery中的Ajax方法获取web service等后台程序中的方法的更多相关文章

  1. ajax异步获取数据后动态向表格中添加数据(行)

    因为某些原因,项目中突然需要做自己做个ajax异步获取数据后动态向表格中添加数据的页面,网上找了半天都没有 看到现成的,决定自己写个例子 1.HTML页面 <!doctype html> ...

  2. 【转载】C#通过IndexOf方法获取某一列在DataTable中的索引位置

    在C#中的Datatable数据变量的操作过程中,有时候需要知道某一个列名在DataTable中的索引位置信息,此时可以通过DataTable变量的Columns属性来获取到所有的列信息,然后通过Co ...

  3. iOS 中client和server的 Web Service 网络通信 (1)

    当你打开你手机上新浪微博应用或者知乎应用是.你是否会去想这些显示在手机上的图片和数据时从哪里来的?又是通过如何的方法实现的?好.那么接下来就介绍是如何实现的.过程又是怎么样的.      当我们浏览着 ...

  4. VB.NET,C#.NET调用Web Service,利用visual studio 的实现方法

    下面是一篇文章比较详细,其实具体操作很简单,把Web Service服务地址,利用工具(VS2010),通过添加引用的形式,添加到项目中来就可以应用了. 大家如果这个地方不会操场的话,可以问问我QQ: ...

  5. jquery插件中使用ajax并且获取使用插件的对象

    jquery插件中使用ajax后无法在里面获取this 解决办法是在函数内使用ajax前声明变量 $this=this 然后再ajax中使用$this

  6. 从web页面启动winform程序的实现方法

    本文实现的需求是: A.通过web页面启动winform程序: B.将页面的参数传递给winform程序: C.winform程序已经启动并正在运行时,从web页面不能重新启动winform程序,只是 ...

  7. 项目中使用WCF替换asmx Web service总结

    以前项目解决方案中,用http协议的asmx Web service作服务器数据访问入口,在SoapHeader中写入用户名和加盐密码进行身份认证. http asmx服务是明文传输,传输过程中数据很 ...

  8. iOS 中client和server的 Web Service 网络通信 (2)

    在实际的应用开发过程中,同步请求的用户体验并非非常好:我们都知道.Apple是非常重视用户体验的.这一点也成为了行业的标杆,没实用户哪里来的好产品.所以用户体验是极其重要的.貌似废话有点多.接下来进入 ...

  9. Vue执行方法,方法获取data值,设置data值,方法传值

    方法写在methods中 v-on:click="run()" @click="run()" 方法获取data中的数据通过this.数据获取 方法设置data中 ...

随机推荐

  1. Java之Property-统获取一个应用程序运行的次数

    package FileDemo; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStre ...

  2. [置顶] Flex中Tree组件无刷新删除节点

    在Tree组件中经常要删除某个节点,而删除之后重新刷新加载该Tree组件会影响整个操作效果和效率,因此,无刷新删除就比较好,既删除了节点也没有刷新tree,而使Tree的状态处于删除之前的状态. 无刷 ...

  3. webService 接口调用配置

    1.配置XML文件,如果新建一个XML文件需要在applicationContext.xm里面配置一下 <import resource="cxf-client.xml" / ...

  4. lua string 库

    --lua中字符串索引从前往后是1,2,……,从后往前是-1,-2……. --string库中所有的function都不会直接操作字符串,只返回一个结果. ---------------------- ...

  5. C# Winform 支持Hex与ASCII输入和切换的文本框

    最近一直在做一个支持串口,TCP,UDP通讯调试的一体化工具(也就是C#串口调试工具 v2.0的第三版),其中涉及到16进制数据和ASCII码的输入,所以继承了TextBox的基础上,写了这个支持He ...

  6. Tomcat无法部署项目

    设置项目的Jdk,compire version 增加java EE 如果有必要,现在项目根目录下放置.mymetadata文件 <?xml version="1.0" en ...

  7. 使用RecyclerView写树形结构的TreeRecyclerView

    简单介绍 android是不提供树形控件的,假设须要使用树形控件.我们应该怎么做呢? 先看效果 上图是一个明显的树形结构 实现原理 在逻辑上,它们是包括关系.数据结构上是多叉树,这是毋庸置疑的. 可是 ...

  8. CircularProgressBar

    https://github.com/semicoder/CircularProgressBar https://github.com/amurani/MeterView

  9. 使用pypi镜像源加速第三方库在线安装

    用easy_install和pip来安装第三方库很方便 它们的原理其实就是从Python的官方源pypi.python.org/pypi 下载到本地,然后解包安装. 不过因为某些原因,访问官方的pyp ...

  10. android134 360 07 归属地查询

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...