Truly
2005-08-17

  • 下载本文的源码(C#) - 25k
  • 下载本文的源码(VB) - 25k

    摘要

    很多时候大家需要使用xmlhttp来实现无刷新的从服务器获取数据,本文以实例代码来介绍本在客户端对WebService的调用

    主要分为3种类型

  • 通过SOAP对WebService进行调用
  • 通过HTTP POST对WebService进行调用
  • 借助MS的webservice.htc简化调用

    注:本文代码均以C#代码作为基础,对于使用VB代码的需要注意WebService的命名空间,详细请看下载链接中源码

    SOAP对WebService进行调用

    <SCRIPT language="JavaScript">
    // Client invoke WebService use SOAP request and response
    function GetHelloWorld_SOAP(i) 
    {
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        var soapMessage, soapData, URL;
        // Set the soap message
        soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; 
        soapMessage += "<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/\">";
        soapMessage += "<soap:Body>"; 
        // Set the data for soap body ---- begin ------
        soapData = "<HelloWorld xmlns=\"http://tempuri.org/\">";
        soapData += "    <i>" + i + "</i>";
        soapData += "</HelloWorld>";
        // Set the data for soap body ----  end  ------
        soapMessage = soapMessage + soapData + "</soap:Body>"; 
        soapMessage = soapMessage + "</soap:Envelope>"; 
        URL = "Service1.asmx"; //可以使用相对地址或完整URL
        xmlhttp.Open("POST",URL, false); 
        xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8"); 
        xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/HelloWorld");
        xmlhttp.send(soapMessage); 
        alert(soapMessage)
        var x =   xmlhttp.responseXML;
        alert(x.childNodes[1].text);
        //那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
        alert(xmlhttp.Status);
        alert(xmlhttp.StatusText);
    }
    </SCRIPT>
    
    JavaScript vbscript  

    通过HTTP POST对WebService进行调用

    <SCRIPT language="JavaScript">
    // Client invoke WebService use HTTP POST request and response
    function GetHelloWorld_HTTPPOST(i) 
    {
        var URL = "http://localhost/WSInvoke/Service1.asmx/HelloWorld";
        var Params = "i=" + i;// Set postback parameters
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.Open("POST",URL, false); 
        xmlhttp.SetRequestHeader ("Content-Type","application/x-www-form-urlencoded"); 
        xmlhttp.SetRequestHeader ("Content-Length",Params.length);
        xmlhttp.send(Params); 
        var x =   xmlhttp.responseXML;
        alert(x.childNodes[1].text);
        //那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
        alert(xmlhttp.Status);
        alert(xmlhttp.StatusText);
    }
    </SCRIPT>
    
    JavaScript vbscript  

    借助MS的webservice.htc简化调用

    webservice.htc是MS提供的一个对webservie常用方法的封装,可以从ms官方网站下载,安装iewebcontrols时也会安装到你的网站根目录下,使用时需要注意路径。请注意代码中body的属性设置,更多对WebService.htc的介绍,点击这里

    <SCRIPT language="JavaScript">
    function Init()
    {
        // establishes a friendly name for a Web service URL
        wsCaller.useService("http://localhost/WSInvoke/Service1.asmx?WSDL","HW");
    }
    function callWS(i)
    {
        wsCaller.HW.callService(Handler_HW, "HelloWorld", i);
    }
    function Handler_HW(result)
    {
        // if there is an error, and the call came from the call() in init()
        if(result.error)
        {
            // Pull the error information from the event.result.errorDetail properties
            var xfaultcode   = result.errorDetail.code;
            var xfaultstring = result.errorDetail.string;
            var xfaultsoap   = result.errorDetail.raw;
            // Add code to handle specific error codes here
        }
        // if there was no error
        else
        {
            document.all.Text1.value = result.value;
        }
    }
    </SCRIPT>
    
    <BODY id="wsCaller" onload="Init()" style="BEHAVIOR:url(webservice.htc)">
    <INPUT type="text" id="Text1" name="Text1">
    <INPUT onclick="callWS(1)" type="button" value="Invoke" id="Button1" name="Button1">
    
     

    Web Service 的完整代码(C#, Service1.asmx.cs)

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Web;
    using System.Web.Services;
    namespace WSInvoke
    {
        /// <SUMMARY>
        /// Summary description for Service1.
        /// </SUMMARY>
        public class Service1 : System.Web.Services.WebService
        {
            public Service1()
            {
                //CODEGEN: This call is required by the ASP.NET Web Services Designer
                InitializeComponent();
            }
            #region Component Designer generated code
            //Required by the Web Services Designer 
            private IContainer components = null;
            /// <SUMMARY>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </SUMMARY>
            private void InitializeComponent()
            {
            }
            /// <SUMMARY>
            /// Clean up any resources being used.
            /// </SUMMARY>
            protected override void Dispose( bool disposing )
            {
                if(disposing && components != null)
                {
                    components.Dispose();
                }
                base.Dispose(disposing);  
            }
            #endregion
            // WEB SERVICE EXAMPLE
            // The HelloWorld() example service returns the string Hello World
            // To build, uncomment the following lines then save and build the project
            // To test this web service, press F5
            [WebMethod]
            public string HelloWorld(int i)
            {
                return "Hello World" + i;
            }
        }
    }
    
     

    测试所用的html页面(Invoke.html)

    <HTML>
     <BODY>
      <INPUT type="button" value="SOAP" onclick="GetHelloWorld_SOAP('1')" id="Button1" name="Button1">
      <INPUT type="button" value="HTTPPOST" onclick="GetHelloWorld_HTTPPOST('2')" id="Button2" name="Button2">
      <INPUT type="button" value="异常测试" onclick="GetHelloWorld_SOAP('')" id="Button3" name="Button3"><BR><BR>
      <INPUT type="button" value="vbSOAP" onclick="vbGetHelloWorld_SOAP('3')" id="Button4" name="Button4">
      <INPUT type="button" value="vbHTTPPOST" onclick="vbGetHelloWorld_HTTPPOST('4')" id="Button5" name="Button5">
     </BODY>
    </HTML>
    
     
    很晚了,先把代码贴上。有空的时候把异步操作再仔细分析一下 :B

    附表1(IXMLHTTPRequest - 属性)

    Name Type Description
    onreadystatechange N/A 指定当就绪状态发生改变时调用的事件处理函数,仅用于异步操作
    readyState Long 异步操作的状态:未初始化(0),正在加载(1),已加载(2),交互(3),已完成(4)
    responseBody Variant 将响应信息正文作为unsigned byte数组返回
    responseStream Variant 将响应信息正文作为一个ADO Stream对象返回
    responseText String 将响应信息正文作为一个文本字符串返回
    responseXML Object 通过XMLDom将响应信息正文解析为XMLDocument对象
    status Long 服务器返回的HTTP状态码
    statusText String 服务器HTTP响应行状态

    附表2(IXMLHTTPRequest - 方法)

    Name Desciption
    abort 取消当前 HTTP 请求
    getAllResponseHeaders 从响应信息中检索所有的标头字段
    getResponseHeader 从响应信息正文中获得一个 HTTP 标头值
    open(method, url, boolAsync, bstrUser, bstrPassword) 打开一个与 HTTP 服务器的连接
    send(varBody) 设定一个请求的标头字段
    setRequestHeader(bstrHeader, bstrValue) 向 HTTP 服务器发送请求。可包含正文。
  • posted on 2006-01-06 09:03  zacard  阅读(446)  评论(0)    收藏  举报