博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在client端通过java script调用Web Service
阅读量:5348 次
发布时间:2019-06-15

本文共 10855 字,大约阅读时间需要 36 分钟。

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

TimeService: GetTime()

None.gif
//
Return time on server
None.gif
        [WebMethod]
None.gif        
public
 
string
 GetTime()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif
{
InBlock.gif            
return DateTime.Now.ToString();
ExpandedBlockEnd.gif        }

 

客户端显示的页面WebForm1:

None.gif
<
HTML
>
None.gif    
<
HEAD
>
None.gif        
<
title
>
WebForm1
</
title
>
None.gif        
<
meta 
name
="GENERATOR"
 Content
="Microsoft Visual Studio .NET 7.1"
>
None.gif        
<
meta 
name
="CODE_LANGUAGE"
 Content
="C#"
>
None.gif        
<
meta 
name
="vs_defaultClientScript"
 content
="JavaScript"
>
None.gif        
<
meta 
name
="vs_targetSchema"
 content
="http://schemas.microsoft.com/intellisense/ie5"
>
ExpandedBlockStart.gifContractedBlock.gif        
<
script 
language
="javascript"
>
dot.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
function timer()dot.gif{
InBlock.gif        service.useService(
"http://localhost/TimeWebService/TimeService.asmx?wsdl","TimeService");
InBlock.gif        service.TimeService.callService(callback,
"GetTime");
InBlock.gif        setTimeout(
"timer()",1000);
InBlock.gif
ExpandedSubBlockEnd.gif    }
InBlock.gif    
ExpandedSubBlockStart.gifContractedSubBlock.gif    
function callback(res)dot.gif{
InBlock.gif        
if (!res.error)
InBlock.gif            time.innerText
=res.value
ExpandedSubBlockEnd.gif    }
ExpandedBlockEnd.gif        
</
script
>
None.gif    
</
HEAD
>
None.gif    
<
body 
MS_POSITIONING
="GridLayout"
 onload
="timer()"
>
None.gif        
<
div 
id
="service"
 style
="BEHAVIOR:url(webservice.htc)"
></
div
>
None.gif        
<
form 
id
="Form1"
 method
="post"
 runat
="server"
>
None.gif            
<
TABLE 
id
="Table1"
 style
="Z-INDEX: 101; LEFT: 8px; WIDTH: 440px; POSITION: absolute; TOP: 8px; HEIGHT: 50px"
None.gif                cellSpacing
="1"
 cellPadding
="1"
 width
="440"
 border
="0"
>
None.gif                
<
TR
>
None.gif                    
<
TD 
style
="WIDTH: 83px"
>
None.gif                        
<
asp:Label 
id
="Label1"
 runat
="server"
>
Current time:
</
asp:Label
></
TD
>
None.gif                    
<
TD
><
span 
id
="time"
></
span
></
TD
>
None.gif                
</
TR
>
None.gif                
None.gif            
</
TABLE
>
None.gif        
</
form
>
None.gif    
</
body
>
None.gif
</
HTML
>

 

其中引入一个名为webservice.htc的文件,它包含了使用java script来调用Web Service的两个方法: 和 。wbservice.htc可以通过以下地址下载:
其实,web service本质上就是http,xml,所以完全可以自己来实现调用Web Service,有兴趣的话可以参考一下webservice.htc中的_invoke()函数:
None.gif
var
 szAction 
=
 oM.soapAction;
None.gif        
if
 (szAction 
!=
 
null
 
&&
 szAction.length 
>
 
0
)
None.gif            oXmlHttp.xmlHttp.setRequestHeader(
"
SOAPAction
"
, '
"
'+szAction+'
"
');
None.gif        oXmlHttp.xmlHttp.setRequestHeader(
"
Content-Type
"
"
text/xml
"
);
None.gif        
var
 sNS 
=
 ' xmlns
=
""
';
None.gif        
for
 (
var
 ns 
in
 oS.ns)
None.gif        {
None.gif            
var
 nsuri 
=
 oS.ns[ns];
None.gif            
if
 (ns 
==
 
""
 
||
 nsuri 
==
 
""
)
None.gif                
continue
;
None.gif            sNS 
+=
  
"
 xmlns:
"
 
+
 ns 
+
 '
=
"
' + nsuri + '
"
';
None.gif        }
None.gif        
var
 szHeader 
=
 encodeHeader(oS, oM, oCall);
None.gif        
var
 szPayload 
=
 
"
<?xml version='1.0'?>\n<SOAP-ENV:Envelope
"
None.gif            
+
 (oM.es 
==
 
null
 
?
 '' : (' SOAP
-
ENV:encodingStyle
=
"
' + oM.es + '
"
'))
None.gif            
+
 sNS 
+
 
"
>\n
"
None.gif            
+
 szHeader
None.gif            
+
 '
<
SOAP
-
ENV:Body
>
'
None.gif            
+
 szParams 
+
 
"
</SOAP-ENV:Body>\n
"
None.gif            
+
 
"
</SOAP-ENV:Envelope>\n
"
;
None.gif        
if
 (co.async)
None.gif        {
None.gif            oCall.oXmlHttp 
=
 oXmlHttp;
None.gif            oXmlHttp.xmlHttp.onreadystatechange 
=
 
function
() {getResult(oCall);};
None.gif            
try
None.gif            {
None.gif                oXmlHttp.xmlHttp.send(szPayload);
None.gif            }
None.gif            
catch
(e)
None.gif            {
None.gif                
return
 postError(oCall, 
5
);
None.gif            }
None.gif            
return
 oCall.id;
None.gif        }
None.gif        
try
None.gif        {
None.gif            oXmlHttp.xmlHttp.send(szPayload);
None.gif        }
None.gif        
catch
(e)
None.gif        {
None.gif            
return
 returnError(oCall, 
5
);
None.gif        }
None.gif        
if
 (oXmlHttp.xmlHttp.responseXML.parseError.errorCode 
!=
 
0
)
None.gif        {
None.gif            _errUnknownS.raw 
=
 oXmlHttp.xmlHttp.responseText;
None.gif            
return
 returnError(oCall, 
4
);
None.gif        }
None.gif        
var
 r;
None.gif        
try
None.gif        {
None.gif            r 
=
 processResult(oCall, oXmlHttp.xmlHttp.responseXML.documentElement);
None.gif        }
None.gif        
catch
 (e)
None.gif        {
None.gif            
return
 returnError(oCall, 
7
);
None.gif        }
None.gif        
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 of the element to which the 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 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 method.

Examples

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

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 of the element to which the behavior is attached.
sFriendlyName Required. The friendly name for the Web Service, which is defined by calling the 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 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 property to true, the return value of the method is an Integer that identifies the instance of the method call. In this case, an 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 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 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 .

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 .

When passing an   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 object. In the following XML data island,
BOOKLIST is the root.

Show Example

16-041
HTML
1998-03-07
127853
Instant HTML
16-048
Scripting
1998-04-21
375298
Instant JavaScript

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;            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.

 

转载于:https://www.cnblogs.com/roger/archive/2004/11/09/61914.html

你可能感兴趣的文章
Java学习--设计模式简介
查看>>
PL/SQL 连接mysql步骤
查看>>
VIM HML
查看>>
socket了解(转)
查看>>
eclipse 技巧
查看>>
JS实现固定在网页右上角3D风格旋转文字
查看>>
crontab
查看>>
如何设置ASP.NET站点页面运行超时
查看>>
TOJ 3151: H1N1's Problem(欧拉降幂)
查看>>
JavaScript sort()方法比较器
查看>>
crawler_大型舆情架构图
查看>>
JDK及JRE简介
查看>>
this关键字剖析
查看>>
【网站收藏】
查看>>
Spring中@相关注解的意义
查看>>
redis事务
查看>>
Redis入门教程(一)
查看>>
举例说明数据结构在网络技术领域和实际生活中的应用
查看>>
SVG.坐标转换_使用CSS
查看>>
广州菁宏信息科技有限公司团队
查看>>