Consume Web Services the straight way—through XMLHttpRequest object

on Saturday, August 8, 2009


Consume Web Services the straight way—through XMLHttpRequest object
As is well known, Web Services can be accessed via the HTTP-based protocol. The great object—XMLHttpRequest, therefore, may be used directly to call Web Services. According to the features of XMLHttpRequest and Web Services and what the client side needs, the whole process can be divided into three detailed steps.

· Send the HTTP requests to Web Services via XMLHttpRequest and get the corresponding HTTP responses.

· Resolve the XML data returned from the server and pick out the needed data.

· Render the acquired data via the client-side JavaScript.

No doubt that the difficulty lies in Step 2—resolving XML in the client side. In this aspect, different browsers have offered different solutions. In Microsoft Internet Explorer, we can achieve our goal by resorting to the ActiveX control—XMLDOM. As for other browsers, such as Mozilla's FireFox, Opera, etc., the third-party script libraries are often borrowed in order to resolve XML data. For example, Google's google ajaxslt can resolve XML and convert XSLT.

Joyfully, to obtain the required data from the XML object returned via Web Services does not need to resolve XML completely. Thus, besides the HTTP protocol scheme, we can use SOAP (Simple Object Access Protocol) to call a Web Service, such as the SOAP-based JavaScript library—soapclient.js. This library can be downloaded from www.guru4.net and the accompanied source codes in this article also provide one. Figure 1 gives us the general depiction of this small framework.

Figure 1: The mechanism of calling web services provided by soapclient.js


This script is so direct and simple to use that we only give a corresponding sample.

First, define the Web service as usual.

Listing 1
[WebMethod]
Public string HelloWorld()
{
Return "Hello World!";
}
Next, write the client-side JavaScript to call the Web service.

Listing 2
function HelloWorld()
{
var pl =new SOAPClientParameters();
SOAPClient.invoke(url, "Hello World", pl, true, HelloWorld_callback);
}
function HelloWorld_callback(r)
{
alert(r);
}
Here, we only illustrate an ABC example; for more complicated ones please refer to the related web site.

0 comments:

Post a Comment