1、建立项目WebService和WebApp项目,如图所示
2、WebService代码为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebService1
{
/// <summary>
/// Service1 的摘要说明
/// </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 Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
//返回a+b的和
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}
[WebMethod]
public int Sum(int x)
{
int sum = 0;
for (int i = 0; i <= x; i++)
{
sum += i;
}
return sum;
}
}
}
3、下载webservice.htc文件,他是微软提供有一个对WebService常用方法的封装,下载后放到WebApp里。
4、调用代码为:
<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" type="text/javascript">
function init() {
//改为自己实际的WebService地址
xhkService.useService("http://localhost:3152/Service1.asmx?wsdl", "calMyMath"); //创建服务对象
}
//调用方法
function callMethod() {
var parm1 = Form1.all.txtA.value; //获取第一个参数
var parm2 = Form1.all.txtB.value; //获取第二个参数
xhkService.calMyMath.callService(callback, "Add", parm1, parm2); //调用WebService里的Add方法
}
//回调函数,处理并显示返回结果
function callback(res) {
if (!res.error)
Form1.all.retValue.value = res.value; //判断返回值
else
Form1.all.retValue.value = '计算错误'; //计算错误
}
</script>
</head>
<body onload="init()">
<div id="xhkService" style="behavior: url(webservice.htc)"></div>
<form id="Form1" method="post" runat="server">
<input type="text" id="txtA" name="txtA" /> + <input type="text" id="txtB" name="txtB" />
<input onclick="callMethod()" type="button" value="=" />
<input type="text" id="retValue" name="retValue" />
</form>
</body>
</html>
运行结果:
分析:
<div id="xhkService" style="behavior: url(webservice.htc)"></div> 在div的id指定一个有意义的名称,这里写为xhkService,以方便在JS里调用, style里制定WebService的行为webservice.htc。xhkService.useService(wsdl路径,简单的命名方式),wsdl路径为自己WebService路径加上参数wsdl,返回XML文档,简单的命名方式,这里起名为calMyMath,
xhkService.calMyMath.callService(callback, "Add", parm1, parm2);
xhkService.calMyMath.callService(回调函数, WebService里的方法, 参数1, 参数2…);如果没有参数可以省略,如调用HelloWorld 方法,xhkService.calMyMath.callService(callback, "HelloWorld");