Ajax学习笔记(3)异步调用web service以及客户端服务器端数据类型转换
2009-06-19 16:07 key_sky 阅读(636) 评论(0) 编辑 收藏 举报一.WebServiceProxy
一.Methods
1.invoke:执行异步调用web service的函数
Sys.Net.WebServiceProxy.invoke(path,methodName,useHttpGet,parameters,succeedCallback,failedCallback,userContext,timeout)
Path:web service的Url地址
methodName:需要执行的web service中的方法名称
useHttpGet:可选参数,默认为false,请求方式为POST,若设置为true,请求方式则为Get
parameters:可选参数,调用的js函数的名称
succeedCallback:可选参数,当请求成功后执行的函数
failedCallback:可选参数,当请求失败后执行的函数
userContext:可选参数,提交的用户相关信息
timeout:可选参数,执行的HTTP请求的等待时间,单位为毫秒
二.WebServiceError
一.Properties
1.exceptionType:获取错误的类型
var errorException:error.get_exceptionType();
2. message:获取错误的提示信息
var message=error.get_message();
3.stackTrace:获取追踪时的错误提示信息
var stackTrace=error.get_stackTrace();
4.statusCode:获取HTTP请求错误提示信息
var statusCode=error.get_statusCode();
5.timeOut:获取因为超时引起的错误信息
var timeout=error.get_timeOut();
三.客户端调用Web Service一般步骤
1.为Web Service添加[ScriptService]方法
2.为Web Service中需要暴露给客户端的方法添加[WebMethod]属性
3.在页面的ScriptManager控件中添加对web service的引用
4.使用客户端调用web service的方法
5.在客户端调用回调函数
6.若需要以HTTP GET方式调用,则修改为[ScriptMethod(UseHttpGet=true)]
7.复杂的数据类型还需要为web service添加[GenerateScriptType(typeof(type))]
四.客户端调用Web Service中DataTable类型
1.调用web service的一般步骤都添加完毕
2.将Ajax CTP的dll引用包复制到bin目录下
3.在web.config配置文件下的web extensions节点下添加如下代码
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000">
<converters>
<add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="DataRowConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</converters>
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
1.调用web service的一般步骤都添加完毕
为web service添加[ScriptMethod(ResponseFormat=ResponseFormat.xml)]
_____________________________________________________________________________________________________
简单调用,错误提示信息以及泛型调用
ConvertComplexData.aspx:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ConvertComplexData</title>
<style type="text/css">
#txtold {
width: 55px;
}
#txtname {
width: 55px;
}
#txtemail {
width: 55px;
}
#divresult
{
background-color:Green;
width:500px;
float:left;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server">
<Services>
<asp:ServiceReference Path="WebService/ComplexType.asmx" />
</Services>
</asp:ScriptManager>
<input id="txtold" type="text" />
<input id="txtname" type="text" />
<input id="txtemail" type="text" />
<button id="btnGetClass" onclick="return GetClass_Click()">GetClass</button>
<button id="btnGetGeneric" onclick="return GetGeneric_Click()">GetGeneric</button>
<div id="divresult"></div>
<script type="text/javascript">
function GetClass_Click() {
var old = $get("txtold").value;
var name = $get("txtname").value;
var email = $get("txtemail").value;
ComplexType.Getkeysky(old, name, email, onGetClassSuccessed,onFailed);
//尽量将web service放到调用页平级或上下级目录下
}
function onGetClassSuccessed(result) {
$get("divresult").innerHTML = "";
$get("divresult").innerHTML += result.name;
$get("divresult").innerHTML += result.email;
$get("divresult").innerHTML += "我的年龄是" + result.old;
}
function onFailed(error) {
$get("divresult").innerHTML = "";
$get("divresult").innerHTML = error.get_exceptionType()+"</br>";
$get("divresult").innerHTML += error.get_message() + "</br>";
$get("divresult").innerHTML += error.get_stackTrace() + "</br>";
}
function GetGeneric_Click() {
ComplexType.GenerIntlist(onGetGenericSuccessed);
}
function onGetGenericSuccessed(result) {
$get("divresult").innerHTML = "";
for (index = 0; index < result.length; ++index) {
$get("divresult").innerHTML += result[index] + "</br>";
}
//对于泛型Ajax异步通信层会自动将返回的值转化为数组
}
</script>
</form>
</body>
</html>
ComplexType.asmx:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
/// <summary>
///ComplexType 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[GenerateScriptType(typeof(keysky))]
//调用复杂数据类型
[ScriptService]
//将web service暴露给客户端脚本
public class ComplexType : System.Web.Services.WebService {
public ComplexType () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public keysky Getkeysky(int old, string name, string email)
{
return new keysky(old, name, email);
}
[WebMethod]
public List<int> GenerIntlist()
{
List<int> mylist = new List<int>();
for(int i=0;i<10;i++)
{
mylist.Add(i);
}
return mylist;
}
}
点击GetClass按钮:
错误提示信息:
点击GetGeneric按钮:
————————————————————————————————————————————————
从客户端得到datatable
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>GetDataTable</title>
<style type="text/css">
#divresult
{
background-color:Silver;
width:500px;
float:left;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server">
<Scripts>
<asp:ScriptReference Path="../js/GetData.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="WebService/GetData.asmx" />
</Services>
</asp:ScriptManager>
列名:<input id="txtname" type="text" />
行数:<input id="txtcount" type="text" />
<button id="btnGetDataTable" onclick="return GetDataTable_Click()">GetDataTable</button>
<div id="divresult"></div>
</form>
</body>
</html>
GetData.asmx:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
/// <summary>
///GetData 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class GetData : System.Web.Services.WebService {
public GetData () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public DataTable GetDataTable(string name, int count)
{
DataTable table = new DataTable(name);
table.Columns.Add(new DataColumn("id", typeof(int)));
table.Columns.Add(new DataColumn(name, typeof(string)));
for (int i = 0; i < count; i++)
{
DataRow DR = table.NewRow();
DR["id"] = i;
DR[name] = string.Format("{0}:{1}", name, i);
table.Rows.Add(DR);
table.AcceptChanges();
}
return table;
}
}
GetData.js:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
function GetDataTable_Click() {
var name = $get("txtname").value;
var count = $get("txtcount").value;
GetData.GetDataTable(name, count, onGetTable, onFailed);
}
function onGetTable(result) {
$get("divresult").innerHTML = "";
var colid = result.columns[0].name;
var colname = result.columns[1].name;
var rows = result.rows;
sbuilder = new Sys.StringBuilder();
sbuilder.append("<table border=1; width=300;>");
//加载表头
sbuilder.append(String.format("<tr><td>{0}</td><td>{1}</td></tr>", colid, colname));
//循环加载数据
for (index = 0; index < rows.length; ++index) {
sbuilder.append(String.format("<tr><td>{0}</td><td>{1}</td></tr>", rows[index][colid], rows[index][colname]));
}
sbuilder.append("</table>");
$get("divresult").innerHTML = sbuilder.toString();
}
//调用成功的回调函数
function onFailed(error) {
$get("divresult").innerHTML = "";
$get("divresult").innerHTML = error.get_exceptionType() + "</br>";
$get("divresult").innerHTML += error.get_message() + "</br>";
$get("divresult").innerHTML += error.get_stackTrace() + "</br>";
}
//调用失败的回调函数
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
//ASP.NET AJAX客户端运行时只有收到所有通过ScriptManager引入的脚本的加载完毕通知后,才能够顺利进行初始化工作
点击GetTable按钮:
——————————————————————————————————————————————————
得到XML类型数据:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<%@ Page Language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ConvertXml</title>
<style type="text/css">
#divresult
{
background-color:Green;
width:500px;
float:left;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server">
<Services>
<asp:ServiceReference Path="WebService/XmlSer.asmx" />
</Services>
</asp:ScriptManager>
<button id="btnGetXml" onclick="return GetXml_Click()">GetXml</button>
<div id="divresult"></div>
<script type="text/javascript">
function GetXml_Click() {
XmlSer.Getkeysky(onSuccessed);
}
function onSuccessed(result) {
$get("divresult").innerText = result.xml;
}
</script>
</form>
</body>
</html>
XmlSer.asmx:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
/// <summary>
///XmlSer 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class XmlSer : System.Web.Services.WebService {
public XmlSer () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public keysky Getkeysky()
{
return new keysky(23, "keysky", "wendichen2007@hotmail.com");
}
}
点击GetXML按钮: