22.12 JavaScript调用Web Service
【实例描述】
Web Service也叫Web服务,是目前很流行的一种网络代码共享手段。可以在自己的网站中调用其他人提供的服务,达到自己网站需要的效果(如在自己的网页中添加天气预报服务)。
【实现代码】
创建服务的代码如下所示(此服务需要在Visual Studio 2005中创建)。
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
// <summary>
// 返回HelloWorld
// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class HelloWorld : System.Web.Services.WebService
{
[WebMethod]
public int Hello_World(int x,int y) {
return x * y;
}
}
用JavaScript调用服务的代码如下所示:
<HTML>
<HEAD>
<title>Javascript</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .Net 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com /intellisense/ie5">
<script language="Javascript">
function callMethod()
{
service.useService("http://localhost/website1/HelloWorld.asmx? wsdl","calService"); //创建服务对象
var parm1 = Form1.all.mul1.value; //获取第一个参数
var parm2 = Form1.all.mul2.value; //获取第二个参数
service.calService.callService(callback,"Hello_World",parm1,parm2); //调用方法
}
function callback(res)
{
if (!res.error)
Form1.all.retValue.value=res.value; //判断返回值
else
Form1.all.retValue.value='计算错误'; //计算错误
}
</script>
</HEAD>
<body>
<div id="service" style="BEHAVIOR:url(webservice.htc)"></div>
<form id="Form1" method="post" runat="server">
<FONT face=宋体><INPUT type=text id=mul1 name=mul1>*<INPUT type=text id=mul2 name=mul2><INPUT style="WIDTH: 50px" onclick=callMethod() type=button value="="><INPUT
type=text id=retValue name=retValue></FONT>
</form>
</body>
</HTML>
【运行效果】
本例中Web服务的运行效果如图22-13所示。JavaScript调用服务的效果如图22-14所示。

图22-13 本例中Web服务的运行效果 图22-14 JavaScript调用服务的效果
【难点剖析】
本例使用了Web Service.htc组件,使用此组件的步骤如下:
(1)先从微软网站上下载Web Service.htc。
(2)把Web Service行为组件绑定到一个html标签。
(3)用Web Service行为组件的useService提供Web Service的地址。
(4)用Web Service行为组件的callService访问Webmethod。
★ 注意 ★
本例需要将所有文件添加到Visual Studio 2005中运行,因为需要指定Web Service的URL,否则运行出现错误。






