Calling web service using AJAX

Green bay, WI - You can actually use several AJAX framework out there that can offer this functionality such as DOJO, DWR and GWT. Websphere also has a javascript framework that you can get here. Bottom line of all AJAX frameworks is just XmlHttpRequest, xml and javascript. This post is my idea on how to build a soap message and use this as a payload to your web service endpoint.

Here is the concept:

1. Create your sample web service:


Basic components you need to build a web service:

a. Service Endpoint Interface
b. Service Endpoint Implementation
c. wsdl file
d. java-wsdl mapping file


2. Build a simple html page with a button. This will be used to invoke the web service endpoint.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">/meta>
<title>AccessSoapWithAJAX</title>
<script src="scripts/AccessSoapWithAJAX.js" type="text/javascript"></script>
</head>
<body>
<form method="get">
<input type="button" οnclick="callWebService()" name="click" value="call web service"/>
<input type="text" name="test" id="test" value="call web service"/>
</form>
</body>
</html>

3. Code your javascript. This includes building the XMLHttpRequest, set appropriate headers and builds your soap message. Here is a simple example:

scripts/AccessSoapWithAJAX.js:

var xmlHttpRequest;

function getXMLHttpRequest()
{
var xmlhttp = null;
try
{ // firefox
xmlhttp = new XMLHttpRequest();
}
catch (e )
{
try
{ // ie
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e )
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}

function callWebService()
{
xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = responseHelloWorld;
var payload = createXML();
var url = "/AsyncJsXML-AsyncJsXML-context-root/HelloWorld";

// open first before setting the headers
xmlHttpRequest.open("POST", url, true);
// set headers
xmlHttpRequest.setRequestHeader('Man',
'POST http://localhost:8988/AsyncJsXML-AsyncJsXML-context-root/HelloWorld HTTP/1.1');
xmlHttpRequest.setRequestHeader('Proxy-Connection', 'Keep-Alive');
xmlHttpRequest.setRequestHeader('Content-type',
'text/xml; charset=UTF-8');
xmlHttpRequest.setRequestHeader('Content-length', '224');
xmlHttpRequest.setRequestHeader('SOAPAction', '');
xmlHttpRequest.send(payload);
}

function responseHelloWorld()
{
if (xmlHttpRequest.readyState == 4)
{
alert(xmlHttpRequest.responseText);
}
}
function createXML()
{

var xmlStr = '<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">';
xmlStr += ' <Body> ';
xmlStr += ' <sayHello xmlns="http://example">';
xmlStr += ' <name>tTest</name> ';
xmlStr += ' </sayHello>';
xmlStr += ' </Body> ';
xmlStr += '</Envelope>';

return xmlStr;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章