使用 XMLHttpRequest 实现 Ajax 四:调用 Webservice

构建 Webservice

 

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService1
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = " http://tempuri.org/ " )]
[WebServiceBinding(ConformsTo
= WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(
false )]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{

[WebMethod]
public int Add( int x, int y)
{
return x + y;
}
}
}

 

 

页面Javascript 如下

 

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
< head runat ="server" >
< title ></ title >
< script language ="javascript" >

function Add() {
var x = document.getElementById( " <%=Text1.ClientID%> " ).value;
var y = document.getElementById( " <%=Text2.ClientID%> " ).value;
var data;
data
= ' <?xml version="1.0" encoding="utf-8"?> ' ;
data
= data + ' <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/"> ' ;
data
= data + ' <soap:Body> ' ;
data
= data + ' <Add xmlns="http://tempuri.org/"> ' ;
data
= data + ' <x> ' + x + ' </x> ' ;
data
= data + ' <y> ' + y + ' </y> ' ;
data
= data + ' </Add> ' ;
data
= data + ' </soap:Body> ' ;
data
= data + ' </soap:Envelope> ' ;

var xmlhttp = new ActiveXObject( " Microsoft.XMLHTTP " );
var URL = " http://localhost:1096/Service1.asmx " ;
xmlhttp.Open(
" POST " , URL, false );
xmlhttp.SetRequestHeader(
" Content-Type " , " text/xml; charset=gb2312 " );
xmlhttp.SetRequestHeader(
" SOAPAction " , " http://tempuri.org/Add " );
xmlhttp.Send(data);
document.getElementById(
" <%=Label1.ClientID%> " ).innerHTML = xmlhttp.responseText;
}

</ script >
</ head >
< body >
< form id ="form1" runat ="server" >
< input id ="Text1" type ="text" runat ="server" />
< input id ="Text2" type ="text" runat ="server" />
< input id ="Button1" type ="button" value ="Add" onclick ="Add()" />
< asp:Label ID ="Label1" runat ="server" Text ="Label" ></ asp:Label >
</ form >
</ body >

 

转载于:https://www.cnblogs.com/waitrabbit/archive/2010/06/27/1766382.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值