AJAX访问WebService

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://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);
}

 

 

回调函数
function ff(){
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
      var result = xmlhttp.responseText;
      alert(result);
   } else alert(xmlhttp.status);     
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值