Standard Web Services pass data using SOAP-based XML. Ajax-enabled web services by default use JSON (which, as we mentioned above, is a lightweight protocol for encrypting Javascript objects), though they can be configured to pass XML.
To set up a web service to be called from Ajax, there are three steps.
1. Setup the environment for the web service.
If the web service is part of an ajax-enabled project then all of the correct settings will have been made. However, if it’s an existing web service that needs to be Ajax enabled there are three things that you have to check to ensure that the environment is supportive.
a. Make sure that the web service project is specifying the appropriate HttpHandler in its web.config. The setting will look something like this:
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
</httpHandlers>
The point of this handler is to check for calls to the webservice which are post-fixed with ‘/js’, for instance
http://localhost/EwanService/Service1.asmx/js
Assuming that the correct attributes have been set on the service (see below), this call will return a javascript proxy object with which the methods service can be called.
b. Make sure that the project references the System.Web.Extensions dll.
c. Make sure that the service has the appropriate security set on it so that it can return data to a call from a web browser.
2. Decorate the service class with the ScriptServiceAttribute. The following gives an example.
|
3. Register the service with the script manager, which can be done declaratively with ‘Services’ and ‘ServiceReference’ tags, like this:
|
(For services which are not in the local project you may need to give a full URL as the Path value).
With all this in place you can then make calls back to the browser by using the appropriately named proxy object (if you’re confused about the extra variables in the signature of the method below then see the previous section):
<a href="javascript:FunWithAjax.WebService1.HelloWorld(echoResult, showError, 'test')">Hello World</a>
It’s important to note, though, that the ability of the client-side code to access web services is restricted to the domain which authors it. There is a general security restriction placed on the XmlHttpRequest object which stops it making calls outside its parent domain. So, for instance, a page served up by http://www.mydomain.com/ can’t make XmlHttpRequest calls out to a web service hosted on http://www.otherdomain.com/. Hence if there is a need to access external web services, these will have to be proxied by a web service located on the parent server.