WebService可以作为AJAX引擎的服务器端,由于WebService使用了两种协议,即SOAP和Http Post协议,这使得我们可以使用两种方式来访问WebService。
WebService代码:
这个代码很简单,就是输入一个数,返回一个数。
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
namespace AJAXWebService
{
/// <summary>
/// Service1 的摘要说明。
/// </summary>
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//CODEGEN: 该调用是 ASP.NET Web 服务设计器所必需的
InitializeComponent();
}
#region 组件设计器生成的代码
//Web 服务设计器所必需的
private IContainer components = null;
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
[WebMethod]
public double CalculateTmp(double ss)
{
return ss*2.3;
}
}
}
我们来看如何访问这个Web服务的CaolulateTmp的方法。首先是走Http Post协议,其代码如下:
var xmlhttp
function ss(){
xmlhttp=getHTTPObject();
xmlhttp.open("post","http://localhost/AJAXWebService/Service1.asmx/CalculateTmp",true);
xmlhttp.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);
xmlhttp.onreadystatechange=ff;
xmlhttp.send("ss=5");
}
function ff(){
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var result = xmlhttp.responseText;
alert(result);
} else alert(xmlhttp.status);
}
}
第二个是使用SOAP协议,代码如下:
function ss(){
xmlhttp=getHTTPObject();
xmlhttp.open("post","http://localhost/AJAXWebService/Service1.asmx",true);
xmlhttp.setRequestHeader(‘Content-Type‘,‘text/xml‘);
xmlhttp.setRequestHeader(‘charset‘,‘utf-8‘);
xmlhttp.setRequestHeader(‘SOAPAction‘,‘http:///CalculateTmp‘);
xmlhttp.onreadystatechange=ff;
var tt;
tt=‘<?xml version="1.0" encoding="utf-8"?>‘;
tt+=‘<soap:Envelope xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:xsd="http://www./2001/XMLSchema" xmlns:soap="http://schemas./soap/envelope/">‘;
tt+=‘<soap:Body>‘;
tt+=‘<CalculateTmp xmlns="http:///">‘;
tt+=‘<ss>15</ss>‘;
tt+=‘</CalculateTmp>‘;
tt+=‘</soap:Body>‘;
tt+=‘</soap:Envelope>‘;
xmlhttp.send(tt);
}
其实说起来很简单,在我们新建一个WebService后,我们是能够查到如何使用这个Web服务的SOAP协议和HTTP Post协议来访问服务的。上面的代码,完全是发送标准请求的内容。
另外,我这次开发的站点可以通过http://60.190.57.69:81/website/MetaWeb/访问,由于领导要求,这个站点实际的功能较之开发的功能有很多屏蔽的地方。不过还好,基本满足了要求。