您的位置:首页 > 编程语言 > ASP

在ASP.NET Atlas中调用Web Service——介绍及简单应用

2006-05-16 11:05 831 查看
作者:Dflying Chen (http://dflying.cnblogs.com/
Atlas Framework中包含了对AJAX调用的封装,让您可以很方便的在客户端通过JavaScript调用服务器端方法。在本篇文章中,我将解释一下如何使用Atlas调用服务器端Web Service。

使用Atlas,我们只需要如下步骤即可调用服务器端Web Service:

在Web Service的方法上加上[WebMethod]属性。
在ASPX页面上的ScriptManager中添加对这个Web Service的引用。

只需以上两步,Atlas会在运行时为您生成相应的mash up,让您可在客户端JavaScript中通过WebServiceClassName.ServiceMethodName()调用该方法。

让我们先来看一个最简单的例子,调用服务器端Web Service得到两个数的和:

首先建立一个Web Service:SimpleWebService.asmx,并在其中添加一个Service Method,不要忘记标记为[WebMethod]哦:

[WebMethod]
public int AddInt(int int1, int int2)
<atlas:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<atlas:ServiceReference Path="SimpleWebService.asmx" />
</Services>
</atlas:ScriptManager>

添加点HTML Code,让用户输入两个整数:
Pass simple type to web service - add the two integers:<br />
<input id="int1" type="text" value="1" size="3" />+
<input id="int2" type="text" value="2" size="3" />=
<input id="btnAddInt" type="button" value="?" onclick="return btnAddInt_onclick()" /><br />
<br />
再书写一点JavaScript,当用户点击上面的按钮时,调用Web Method。这里要注意的是JavaScript中调用Web Method的格式:前面两个参数int1,int2分别对应着Web Service声明中的两个参数,后面一个参数onAddIntComplete表示方法成功返回时的Callback方法,也就是所谓AJAX中的A。同时需要注意的是$()方法,等同于document.getElementById()。

public class ComplexNumber
[WebMethod]
public ComplexNumber AddComplexNumber(ComplexNumber num1, ComplexNumber num2)
Pass complex type to web service - add the two complex numbers:<br />
(<input id="cplx1r" type="text" value="1" size="3" />+
<input id="cplx1i" type="text" value="2" size="3" />i) + (
<input id="cplx2r" type="text" value="3" size="3" />+
<input id="cplx2i" type="text" value="4" size="3" />i) =  
<input id="btnAddComplex" type="button" value="?" onclick="return btnAddComplex_onclick()" />
<br />
然后是相应的JavaScript,当用户点击上面的按钮时,执行这段JavaScript以调用Web Method。

function btnAddComplex_onclick() {
function onAddComplextNumberComplete(result) {
$('btnAddComplex').value = result.Real.toString() + ' + ' + result.Imag.toString() + 'i';
}
浏览器中运行一下,初始化:



点击第一个问号,调用AddInt () Web Method计算1+2,得到3:



点击第二个问号,调用AddComplexNumber () Web Method计算(1+2i) + (3+4i),得到4+6i:



源代码可以在此下载:http://files.cnblogs.com/dflying/SimpleWebServiceDemo.zip

通过以上两个示例,您已经了解了如何与服务器端Web Service进行复杂通信。但实际开发中,往往还需要进行一些其它的处理,例如对服务器的错误信息的处理,对超时的处理,对用户取消操作的处理等等。Atlas同样提供了对以上需求的内建的支持。在后续文章中,我将全面介绍Atlas对Web Service的mash up中对上述复杂情况的处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐