<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="_Default"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>JS 呼叫 WebService</title> <script language=javascript> function RequestByGet(Namestr) ...{ var Name=document.form1.txtName.value; var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); var URL="http://localhost/AspWebSite/WebService.asmx/SayHelloTo?Name=HOOK"; xmlhttp.Open("GET",URL,false); xmlhttp.SetRequestHeader("Content-Type","text/xml;charset=utf-8"); xmlhttp.SetRequestHeader("SOAPAction","http://tempuri.org/SayHelloTo"); xmlhttp.Send(Namestr); alert(xmlhttp.status); if(xmlhttp.status==200) ...{ document.write(xmlhttp.responseText); } } function RequestByGet1() ...{ var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); var URL="http://localhost/AspWebSite/WebService.asmx/SayHelloTo?Name=HOOK"; xmlhttp.Open("GET",URL,false); xmlhttp.Send(); alert(xmlhttp.status); if(xmlhttp.status==200) ...{ document.write(xmlhttp.responseText); } } function RequestByPost(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 +'<SayHelloTo xmlns="http://tempuri.org/">'; data = data +'<Name>'+value+'</Name>'; data = data +'</SayHelloTo>'; data = data +'</soap:Body>'; data = data +'</soap:Envelope>'; var xmlhttp =new ActiveXObject("Microsoft.XMLHTTP"); var URL="http://localhost/AspWebSite/WebService.asmx"; xmlhttp.Open("POST",URL, false); xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=gb2312"); xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHelloTo"); xmlhttp.Send(data); document.write( xmlhttp.responseText); } </script> </head> <body> <form id="form1" runat="server"> <div> <br /> <input id="txtName" type="text"/><br /> <br /> <input id="btnGet" type="button" value="Get" onclick="RequestByGet1('Ya')"/> <input id="btnPost" type="button" value="Post" onclick="RequestByPost('Ming')"/></div> </form> </body> </html>
WebServices:
using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; /**////<summary> /// Summary description for WebService ///</summary> [WebService(Namespace ="http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] publicclass WebService : System.Web.Services.WebService ...{ public WebService () ...{ //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] publicstring HelloWorld() ...{ return"Hello World"; } [WebMethod] publicstring SayHelloTo(string Name) ...{ return"Hello "+ Name; } }