客户端xmlhttp调用webservice

<script language="JavaScript" type="text/javascript"> function doClick(index, numTabs, id) { document.all("tab" + id, index).className = "tab"; for (var i=1;eval(i + decodeURI("%3c") + numTabs); i++) { document.all("tab" + id, (index + i) % numTabs).className = "backtab"; } document.all("code" + id, index).style.display = ""; for (var j=1; eval(j + decodeURI("%3c") + numTabs); j++) { document.all("code" + id, (index + j) % numTabs).style.display = "none"; } } </script>

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>
                            
    JavaScriptvbscript 

    通过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>
                            
    JavaScriptvbscript 

    借助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" οnlοad="Init()" style="BEHAVIOR:url(webservice.htc)">
                            <INPUT type="text" id="Text1" name="Text1">
                            <INPUT οnclick="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" οnclick="GetHelloWorld_SOAP('1')" id="Button1" name="Button1">
                            <INPUT type="button" value="HTTPPOST" οnclick="GetHelloWorld_HTTPPOST('2')" id="Button2" name="Button2">
                            <INPUT type="button" value="异常测试" οnclick="GetHelloWorld_SOAP('')" id="Button3" name="Button3"><BR><BR>
                            <INPUT type="button" value="vbSOAP" οnclick="vbGetHelloWorld_SOAP('3')" id="Button4" name="Button4">
                            <INPUT type="button" value="vbHTTPPOST" οnclick="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 服务器发送请求。可包含正文。
 来自: http://truly.cnblogs.com/archive/2005/08/18/218102.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值