不进则退

Roger's blog @cnblogs

导航

在client端通过java script调用Web Service

以下代码实现了在客户端用java script调用Web Service,通过对Web Service:TimeService中GetTime()方法的调用,在客户端显示服务器当前时间,并且以1秒为间隔自动刷新。

TimeService: GetTime()

//Return time on server
        [WebMethod]
        
public string GetTime()
        
{
            
return DateTime.Now.ToString();
        }

 
客户端显示的页面WebForm1:

<HTML>
    
<HEAD>
        
<title>WebForm1</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
        
<script language="javascript">
    
function timer(){
        service.useService(
"http://localhost/TimeWebService/TimeService.asmx?wsdl","TimeService");
        service.TimeService.callService(callback,
"GetTime");
        setTimeout(
"timer()",1000);

    }

    
    
function callback(res){
        
if (!res.error)
            time.innerText
=res.value
    }

        
</script>
    
</HEAD>
    
<body MS_POSITIONING="GridLayout" onload="timer()">
        
<div id="service" style="BEHAVIOR:url(webservice.htc)"></div>
        
<form id="Form1" method="post" runat="server">
            
<TABLE id="Table1" style="Z-INDEX: 101; LEFT: 8px; WIDTH: 440px; POSITION: absolute; TOP: 8px; HEIGHT: 50px"
                cellSpacing
="1" cellPadding="1" width="440" border="0">
                
<TR>
                    
<TD style="WIDTH: 83px">
                        
<asp:Label id="Label1" runat="server">Current time:</asp:Label></TD>
                    
<TD><span id="time"></span></TD>
                
</TR>
                
            
</TABLE>
        
</form>
    
</body>
</HTML>

 

其中引入一个名为webservice.htc的文件,它包含了使用java script来调用Web Service的两个方法:useServicecallService。wbservice.htc可以通过以下地址下载:
http://msdn.microsoft.com/workshop/author/webservice/webservice.htc

其实,web service本质上就是http,xml,所以完全可以自己来实现调用Web Service,有兴趣的话可以参考一下webservice.htc中的_invoke()函数:

var szAction = oM.soapAction;
        
if (szAction != null && szAction.length > 0)
            oXmlHttp.xmlHttp.setRequestHeader(
"SOAPAction", '"'+szAction+'"');
        oXmlHttp.xmlHttp.setRequestHeader(
"Content-Type""text/xml");
        
var sNS = ' xmlns=""';
        
for (var ns in oS.ns)
        {
            
var nsuri = oS.ns[ns];
            
if (ns == "" || nsuri == "")
                
continue;
            sNS 
+=  " xmlns:" + ns + '="' + nsuri + '"';
        }
        
var szHeader = encodeHeader(oS, oM, oCall);
        
var szPayload = "<?xml version='1.0'?>\n<SOAP-ENV:Envelope"
            
+ (oM.es == null ? '' : (' SOAP-ENV:encodingStyle="' + oM.es + '"'))
            
+ sNS + ">\n"
            
+ szHeader
            
+ '<SOAP-ENV:Body>'
            
+ szParams + "</SOAP-ENV:Body>\n"
            
+ "</SOAP-ENV:Envelope>\n";
        
if (co.async)
        {
            oCall.oXmlHttp 
= oXmlHttp;
            oXmlHttp.xmlHttp.onreadystatechange 
= function() {getResult(oCall);};
            
try
            {
                oXmlHttp.xmlHttp.send(szPayload);
            }
            
catch(e)
            {
                
return postError(oCall, 5);
            }
            
return oCall.id;
        }
        
try
        {
            oXmlHttp.xmlHttp.send(szPayload);
        }
        
catch(e)
        {
            
return returnError(oCall, 5);
        }
        
if (oXmlHttp.xmlHttp.responseXML.parseError.errorCode != 0)
        {
            _errUnknownS.raw 
= oXmlHttp.xmlHttp.responseText;
            
return returnError(oCall, 4);
        }
        
var r;
        
try
        {
            r 
= processResult(oCall, oXmlHttp.xmlHttp.responseXML.documentElement);
        }
        
catch (e)
        {
            
return returnError(oCall, 7);
        }
        
return r;


以下是userService和callService方法的详细说明:


useService Method


Establishes a friendly name for a Web Service URL, which can then be referenced from script.

Syntax

sElementID.useService(sWebServiceURL, sFriendlyName [, oUseOptions])

Parameters

sElementID Required. The id of the element to which the WebService behavior is attached.
sWebServiceURL Required. String specifying the URL of the Web Service, using one of the following path types. See the examples section, where several variations of this parameter are shown.
Web Service file name A Web service file, which has an .asmx file extension. This short form of the URL is sufficient, provided that the Web service is located in the same folder as the Web page using the WebService behavior. In this case, the ?WSDL query string is assumed by the behavior.
WSDL file name A Web Services Description Language (WSDL) file name. The WSDL file must have a .wsdl file extension.
Full file path Full path to a WebService (.asmx) or WSDL (.wsdl) file. A file path to a Web Service must include the ?WSDL query string. Either a local file path or a URL can be specified.
Relative path A relative path to a WebService (.asmx) or WSDL (.wsdl) file. A file path to a Web Service must include the ?WSDL query string.
sFriendlyName Required. String representing a friendly name for the Web Service URL.
oUseOptions Optional. An instance of the useOptions object.

Return Value

No return value.

Remarks

After using this method, the identifier specified in sFriendlyName can be used in script as a reference to the Web Service specified by sWebServiceURL.

The useOptions object can be used when it is necessary to retain the Secure Sockets Layer (SSL) authentication for multiple remote method invocations. For code samples illustrating the use of this technique, see the createUseOptions method.

Examples

The following sample defines the friendly name MyMath from the URL specified in the sWebServiceURL parameter.

<script language="JavaScript">
function init()
{
    service.useService("math.asmx?WSDL","MyMath");
}
</script>
<body onload="init()">
<div id="service" style="behavior:url(webservice.htc)">
</div>
</body>

The following examples illustrate various valid forms of the sWebServiceURL parameter.

The following code snippet illustrates the short form of sWebServiceURL. In this case, the math.asmx file must be located in the same folder as the Web page.

service.useService("math.asmx","MyMath");

The following code snippet illustrates how a WSDL file can be specified for the sWebServiceURL parameter. In this case, the conversion.wsdl file must be located in the same folder as the Web page.

service.useService("conversion.wsdl","MyConverter");

The following code snippet defines the sWebServiceURL parameter as a local file. In this case the ?WSDL query string must be included.

service.useService("C:\inetpub\wwwroot\myproject\myws.asmx?WSDL","MyMath");

The following code snippet defines the sWebServiceURL parameter as the full HTTP file path to the myws.asmx Web service file. In this case the ?WSDL query string must be included.

service.useService("http://localhost/myproject/myws.asmx?WSDL","MyMath");

The following code snippet defines the sWebServiceURL parameter as a relative file path to the myws.asmx Web service file. In this case the ?WSDL query string must be included. This example points to a Web Service file two levels up from the Web page.

service.useService("../../myws.asmx?WSDL","MyMath");

The following code snippet defines the sWebServiceURL parameter as a relative file path to the myws.asmx Web service file. In this case the ?WSDL query string must be included. The path points to the myws.asmx Web Service, which is located in the wsfld subfolder of the Web page.

service.useService("./wsfld/myws.asmx?WSDL","MyMath");



callService Method


Invokes a method that is implemented on a Web Service.

Syntax

iCallID = sElementID.sFriendlyName.callService( [oCallHandler], fo, oParam)

Parameters

sElementID Required. The id of the element to which the WebService behavior is attached.
sFriendlyName Required. The friendly name for the Web Service, which is defined by calling the useService method.
oCallHandler Optional. Name of a script callback function that handles the results returned from this instance of the method call.
fo Required. One of the following possible values.
strFuncName A String representing the name of the remote function being called. The String must be bounded by single or double quotation marks.
objCall A call object, which has the necessary properties defined to call a remote function.
oParam Required. One or more comma-delimited parameters, which are passed to the method name specified by fo.

Return Value

In the case of asynchronous communication, returns an Integer, which is a unique identifier for the instance of the method call. In the case of synchronous communication, returns a result object.

Remarks

Using this method causes the WebService behavior to invoke a remote method call on a Web Service.

When the callService method invokes asynchronous communication between the WebService behavior and the Web Service by setting the async property to true, the return value of the method is an Integer that identifies the instance of the method call. In this case, an onresult event handler or callback function should be used to process the returned results.

When the callService method invokes synchronous communication between the WebService behavior and the Web Service by setting the async property to false, the return value of the method is a result object.

For an example of using both synchronous and asynchronous communication between the WebService behavior and the Web Service, see the examples on the call object page.

If oCallHandler is not specified, then an onresult event handler is used to examine the results of the callService. Using this approach, the properties of the event object can be examined to determine if the call was made successfully.

If oCallHandler is specified, then a callback handler function is used to process the results of the method call. The result object is passed to the first parameter of the callback function, so the user specifies the name of the object in the script code. Code samples using each approach are given in Using the WebService Behavior.

Regardless of the type of function used to process the results, the properties exposed to script are similar. If an event handler is used, the syntax used to access result information is event.result. If the callback approach is used, the object name is the name of the first parameter in the callback function declaration. For a comprehensive list of property objects returned by a WebService behavior call, see onresult.

When passing an XmlElement World Wide Web link object to a web service using oParam, the Extensible Markup Language (XML) contained in the XmlElement must contain a single root node. The root node is not returned by the result object. In the following XML data island, BOOKLIST is the root.

Show Example

The following example shows a call to a web service. The element where the WebService Behavior is attached has an id of aaa and the friendly name for the web service is tst.

var x = myXMLElement.documentElement;      // get the xmlelement object
      aaa.tst.callService(myCallBackFunction,"XmlEcho",x);                  

This callback function returns the first child of the booklist element by asking for the zero element child. There is no way to ask for the root or booklist element as it has no parent element.

function myCallBackFunction(res) {
      if (!res.error) {
            var x = res.value;
            var y = x.selectNodes("BOOKLIST")[0].xml;
            alert(y);
      }else{
            alert(res.errorDetail.string);
      }
}

Example

The following example shows how a method named add can be called to calculate the sum of two integers.

<script language="JavaScript">
var iCallID;

function init()
{
    service.useService("/services/math.asmx?WSDL","MyMath");
    iCallID = service.MyMath.callService("add",5,6);
}
</script>
<body onload="init()">
<div id="service" style="behavior:url(webservice.htc)">
</div>
</body>

 

posted on 2004-11-09 13:47  Roger Wo  阅读(9832)  评论(5编辑  收藏  举报