For this article we need to create a web service and a web site. Assume that our web service includes these methods... [WebMethod]
public string HelloWorld() {
return "Hello World";
}
//This method takes your birth year, month and day,
//calculates your age and return the year.
[WebMethod]
public string GetAge(int year, int month, int day) {
DateTime birthDate = new DateTime(year, month, day);
long age = new DateTime(DateTime.Now.Ticks - birthDate.Ticks).Year - 1;
return "You are " + age.ToString() + " years old.";
}
//This method caches the datetime for 4 seconds.
//also a simple cache implementation.
private const int CacheTime = 4; // seconds
[WebMethod(CacheDuration = CacheTime,
Description = "As simple as it gets - the ubiquitous Get Date Time.")]
public string GetDateTime() {
return DateTime.Now.ToString();
}
<html>
<head>
<title>Hello World</title>
<script language="JavaScript">
var iCallID;
function InitializeService(){
service.useService("http://localhost:1394/MyWebService.asmx?wsdl", "HelloWorldService");
service.HelloWorldService.callService("HelloWorld");
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service" style="behavior:url(webservice.htc)" onresult="ShowResult()"> </body>
</html>
2. GetAge.htm (calls GetAge method, takes 3 parameters) <html>
<head>
<title>UseSwap</title>
<script language="JavaScript">
function InitializeService(){
service.useService("http://localhost:1394/MyWebService.asmx?wsdl", "GetAgeService");
}
var StrYear, StrMonth, StrDay;
function GetAge(){
StrYear = document.DemoForm.StringYear.value;
StrMonth = document.DemoForm.StringMonth.value;
StrDay = document.DemoForm.StringDay.value;
service.GetAgeService.callService("GetAge", StrYear, StrMonth, StrDay);
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service" style="behavior:url(webservice.htc)" onresult="ShowResult()">
<form name="DemoForm">
Year : <input type="text" name="StringYear"/>
Month : <input type="text" name="StringMonth"/>
Day : <input type="text" name="StringDay"/>
<button onclick="GetAge()">Get Age</button>
</form>
</body>
</html>
3. GetDateTime.htm (returns cached value) <html>
<head>
<meta http-equiv="refresh" content="2" />
<title>Get Date Time</title>
<script language="JavaScript">
var iCallID;
function InitializeService(){
service.useService("http://localhost:1394/MyWebService.asmx?wsdl", "GetDateTimeService");
service.GetDateTimeService.callService("GetDateTime");
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service" style="behavior:url(webservice.htc)" onresult="ShowResult()">
</body>
</html>
发表于 @ 2007年04月17日 11:36:00 | 评论( loading... ) | 举报| 收藏