用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>
以上是直接贴代码,仅供初学者使用,哈哈,我也菜鸟一个,相互学些
用JQuery中的Ajax方法获取web service等后台程序中的方法的更多相关文章
- ajax异步获取数据后动态向表格中添加数据(行)
因为某些原因,项目中突然需要做自己做个ajax异步获取数据后动态向表格中添加数据的页面,网上找了半天都没有 看到现成的,决定自己写个例子 1.HTML页面 <!doctype html> ...
- 【转载】C#通过IndexOf方法获取某一列在DataTable中的索引位置
在C#中的Datatable数据变量的操作过程中,有时候需要知道某一个列名在DataTable中的索引位置信息,此时可以通过DataTable变量的Columns属性来获取到所有的列信息,然后通过Co ...
- iOS 中client和server的 Web Service 网络通信 (1)
当你打开你手机上新浪微博应用或者知乎应用是.你是否会去想这些显示在手机上的图片和数据时从哪里来的?又是通过如何的方法实现的?好.那么接下来就介绍是如何实现的.过程又是怎么样的. 当我们浏览着 ...
- VB.NET,C#.NET调用Web Service,利用visual studio 的实现方法
下面是一篇文章比较详细,其实具体操作很简单,把Web Service服务地址,利用工具(VS2010),通过添加引用的形式,添加到项目中来就可以应用了. 大家如果这个地方不会操场的话,可以问问我QQ: ...
- jquery插件中使用ajax并且获取使用插件的对象
jquery插件中使用ajax后无法在里面获取this 解决办法是在函数内使用ajax前声明变量 $this=this 然后再ajax中使用$this
- 从web页面启动winform程序的实现方法
本文实现的需求是: A.通过web页面启动winform程序: B.将页面的参数传递给winform程序: C.winform程序已经启动并正在运行时,从web页面不能重新启动winform程序,只是 ...
- 项目中使用WCF替换asmx Web service总结
以前项目解决方案中,用http协议的asmx Web service作服务器数据访问入口,在SoapHeader中写入用户名和加盐密码进行身份认证. http asmx服务是明文传输,传输过程中数据很 ...
- iOS 中client和server的 Web Service 网络通信 (2)
在实际的应用开发过程中,同步请求的用户体验并非非常好:我们都知道.Apple是非常重视用户体验的.这一点也成为了行业的标杆,没实用户哪里来的好产品.所以用户体验是极其重要的.貌似废话有点多.接下来进入 ...
- Vue执行方法,方法获取data值,设置data值,方法传值
方法写在methods中 v-on:click="run()" @click="run()" 方法获取data中的数据通过this.数据获取 方法设置data中 ...
随机推荐
- MySQL在线备份与恢复工具 --> Xtrabackup
1 Xtrabackup原理简介 xtrabackup是一个对InnoDB做数据备份的工具,支持在线热备份(备份时不影响数据读写),是商业备份工具InnoDB Hotbackup的一个很好的替代品. ...
- 曾经的pc端项目踩到的一些兼容性的坑及其解决方案
曾经公司pc端项目一直最低兼容到IE7,要求和chrome下浏览效果一致,真心坑坏了我和另外一个小伙伴(另一个小伙伴以前也没处理过兼容问题).不过还好,在这里真心感谢鑫哥博客的详解,从底层原理讲到了具 ...
- 【Stage3D学习笔记续】山寨Starling(四):渲染代码实现及测试程序
本章会实现最核心的代码,所以涉及点会比较多,这里会发布一个版本,方便日后的回退查看. 点击下载:https://codeload.github.com/hammerc/hammerc-study-St ...
- C++学习笔记(十三):类、包和接口
看标题感觉这些术语和C++没有什么关系啊,包和接口是Java等语言加入的概念. 这篇文章是基于Java等语言的新概念(相对于C++来说的新概念)来看C++的设计思路. 类: C++中,一个文件可以包含 ...
- ThinkPHP中URL解析原理,以及URL路由使用教程!
几个概念: THINKPHP 是一个MVC框架,使用PATHINFO解析出分组名,模块名,方法名,以及参数. PATHINFO:就是 http://localhost/index.php/Home/I ...
- go操作数据库 Go-SQL-Driver/MySQL 使用详解
go操作mysql的驱动包很多,这里讲解当下比较流行的Go-SQL-Driver/MySQL1.下载安装 执行下面两个命令: 下载:go get github.com/Go-SQL-Driver/My ...
- Effective C++ 条款45
本节条款的题目是运用成员模板接受全部兼容类型 作者阐述自己的观点是通过智能指针的样例. 在学习本节条款之前我们要先明确关于隐式转化的问题 例如以下代码: #include<iostream> ...
- leetcode解决问题的方法||Integer to Roman问题
problem: Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range ...
- 设计模式 - 命令模式(command pattern) 多命令 具体解释
命令模式(command pattern) 多命令 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考命令模式: http://blog.csdn.ne ...
- php中body下出现莫名空白字符
php中body下出现莫名空白字符,出现原因 1. 模板前面有莫名格式空格,删不掉,必须把模板里面东西复制出来,新建一个文件弄进去,覆盖原有的 2.docutype前面出现代码,也会导致此问题(有可能 ...