WebService可以作為AJAX引擎的服務(wù)器端,由于WebService使用了兩種協(xié)議,即SOAP和Http Post協(xié)議,這使得我們可以使用兩種方式來訪問WebService。
WebService代碼:
這個代碼很簡單,就是輸入一個數(shù),返回一個數(shù)。
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: 該調(diào)用是 ASP.NET Web 服務(wù)設(shè)計器所必需的
InitializeComponent();
}
#region 組件設(shè)計器生成的代碼
//Web 服務(wù)設(shè)計器所必需的
private IContainer components = null;
/// <summary>
/// 設(shè)計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內(nèi)容。
/// </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服務(wù)的CaolulateTmp的方法。首先是走Http Post協(xié)議,其代碼如下:
var xmlhttp
function ss(){
xmlhttp=getHTTPObject();
xmlhttp.open("post","http://localhost/AJAXWebService/Service1.asmx/CalculateTmp",true);
xmlhttp.setRequestHeader(‘Content-Type‘,‘a(chǎn)pplication/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協(xié)議,代碼如下:
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://tempuri.org/CalculateTmp‘);
xmlhttp.onreadystatechange=ff;
var tt;
tt=‘<?xml version="1.0" encoding="utf-8"?>‘;
tt+=‘<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">‘;
tt+=‘<soap:Body>‘;
tt+=‘<CalculateTmp xmlns="http://tempuri.org/">‘;
tt+=‘<ss>15</ss>‘;
tt+=‘</CalculateTmp>‘;
tt+=‘</soap:Body>‘;
tt+=‘</soap:Envelope>‘;
xmlhttp.send(tt);
}
其實說起來很簡單,在我們新建一個WebService后,我們是能夠查到如何使用這個Web服務(wù)的SOAP協(xié)議和HTTP Post協(xié)議來訪問服務(wù)的。上面的代碼,完全是發(fā)送標(biāo)準(zhǔn)請求的內(nèi)容。
另外,我這次開發(fā)的站點可以通過http://60.190.57.69:81/website/MetaWeb/訪問,由于領(lǐng)導(dǎo)要求,這個站點實際的功能較之開發(fā)的功能有很多屏蔽的地方。不過還好,基本滿足了要求。