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

 

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

转载于:https://www.cnblogs.com/StevenDu/p/ajax.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/399796.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WordPress路径相关函数总结

WordPress路径相关函数总结 wordpress各种获取路径和URl地址的函数总结 wp_upload_dir() 返回WordPress上传目录的地址&#xff0c;是一个数组&#xff0c;包含一系列与上传地址相关的信息。 <?php $upload_dir wp_upload_dir(); ?>

WordPress后台添加侧边栏菜单

https://my.oschina.net/shunshun/blog/78193 https://www.ludou.org/add-admin-menu-in-wordpress.html 添加WordPress顶级管理菜单其实也是一件非常简单的事情&#xff0c;使用两个WordPress内置函数就可以解决问题&#xff0c;分别是add_menu_page()和 add_action()&#xf…

如何看待和选择基础设施软件

1&#xff0c; 广泛性 2&#xff0c; 通用性 3&#xff0c; 稳定性 4&#xff0c; 功能 5&#xff0c; 遇到问题能否快速查到资料 6&#xff0c; 文档是否齐全 不一定是最先进的技术就是最好的。 采用什么样的技术栈&#xff1a; 一定要主流&#xff0c; 很少做到技术专家的地步…

Android 常见错误

2019独角兽企业重金招聘Python工程师标准>>> 1. org.apache.http.conn.HttpHostConnectException: Connection to refused 权限问题: <uses-permission android:name"android.permission.INTERNET"/> 2. 浏览器直接输入url可以get&#xff0c;http …

使用BootStrap框架设置全局CSS样式

一、排版 标题 HTML 中的所有标题标签&#xff0c;<h1> 到 <h6> 均可使用。另外&#xff0c;还提供了 .h1 到 .h6 类&#xff0c;为的是给内联&#xff08;inline&#xff09;属性的文本赋予标题的样式。 <h1>这是一个h1标签</h1><h2>这是一个h2…

SVN初步学习教程

本文目的 让未使用过版本控制器软件或者未使用过subversion软件的人员尽快上手。 subversion的使用技巧很多&#xff0c;这里只总结了最小使用集&#xff0c;即主要的基本功能&#xff0c;能够用来应付日常工作。 因此不涉及subversion服务器端的搭建和配置。 为什么要使用版本…

wordpress 添加自定义的一定级菜单

//添加项级菜单 function register_bwp_menu_page(){ add_menu_page( title标题, 菜单标题, administrator, ../wp-content/themes/yourthemes/myplugin/myplugin-index.php,,,100); } add_action(admin_menu, register_bwp_menu_page); myplugin目录为 yourthemes 主题目…

V2EX大牛的指点

2019独角兽企业重金招聘Python工程师标准>>> first&#xff1a; 我认识一些深圳、杭州、北京的朋友&#xff0c;他们往往更关注以下内容&#xff1a; 1. 代码&#xff08;包括注释&#xff09;的规范性、可维护性 2. 参与一些算法的研究与实现、开源库的创建与维护…

python-实现动态web服务器

# encodingutf-8 import socket from multiprocessing import Process import re import sys# 设置静态文件根目录 HTML_ROOT_DIR ./htmlWSGI_PYTHON_DIR ./wsgipythonclass HTTPServer(object):def __init__(self, application):self.server_socket socket.socket(socket.A…

Android中shape的使用

本人在美工方面一直是比较白痴的&#xff0c;对于一些颜色什么乱七八糟的非常头痛&#xff0c;但是在Android编程中这又是经常涉及到的东西&#xff0c;没办法&#xff0c;只有硬着头皮上。 Android中常常使用shape来定义控件的一些显示属性&#xff0c;今天看了一些shape的使用…

PHP遍历数组的几种方法

这三种方法中效率最高的是使用foreach语句遍历数组。从PHP4开始就引入了foreach结构&#xff0c;是PHP中专门为遍历数组而设计的语句&#xff0c;推荐大家使用。先分别介绍这几种方法 PHP中遍历数组有三种常用的方法&#xff1a; 一、使用for语句循环遍历数组&#xff1b; 二、…

Jmeter集合ant进行操作

1、下载ant包 地址【http://ant.apache.org/bindownload.cgi】 2、解压后&#xff0c;配置ant的环境变量&#xff0c;如下图 3、修改jmeter/extras中的build.xml的文件 代码如下&#xff1a; <?xml version"1.0" encoding"UTF-8"?><project nam…

五种常见的 PHP 设计模式

设计模式只是为 Java™ 架构师准备的 —— 至少您可能一直这样认为。实际上&#xff0c;设计模式对于每个人都非常有用。如果这些工具不是 “架构太空人” 的专利&#xff0c;那么它们又是什么&#xff1f;为什么说它们在 PHP 应用程序中非常有用&#xff1f;本文解释了这些问题…

jquery 点击事件

$("#id").click(function() {alert(alert);});

linux常见命令的常用方法示例

本文涉及命令&#xff1a;date,clock,hwclock,cal,ls,cd,pwd,tty,whereis,which,stat,echo,shutdown,halt,reboot,poweroff,who,w,whami部分命令结果等同&#xff0c;合到一起示例一、Date 打印或设置系统日期和时间1、date &#xff1a;查看当前系统日期和时间2、date %a:查看…

Leetcode: LRU Cache

题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(k…

Day-17: 网络编程

---恢复内容开始--- 现有的互联网通讯方式&#xff0c;是服务器端的进程与客户端进程的通信。Python中进行网络编程&#xff0c;就是在Python程序本身这个进程内&#xff0c;连接别的服务器进程的通信端口进行通信。 互联网协议上包含了上百种协议标准&#xff0c;但是&#xf…

启动MySQL报错

当在linux系统中启动mysql服务的时候service mysqld start时 报&#xff1a;Another MySQL daemon already running with the same unix socket. 解决办法。 原因多个Mysql进程使用了同一个socket。 两个方法解决&#xff1a; 第一个是立即关机 使用命令 shutdown -h now 关机&…

计算机应用基础教程作业脑图 车辆工程学院 冯大昕

转载于:https://www.cnblogs.com/FengTang/p/7553055.html

UML该元素的行为为基础的元素

&#xfeff;&#xfeff;Behavioral thingsare the dynamic parts of UML models. These are the verbs of a model, representing behavior over time and space. In all, there are three primary kinds of behavioral things. 行为元件是UML模型的动态部分&#xff0e;它们…