In last posts , we had shown the example Creating your first REST service using Jersey. Then we introduced to making the Rest call from JavaScript.
The example which we had shown was for asynchronous request. Now let us assume that you want to make an asynchronous call . How will it work out ?
Option A : Let the call be asynchronous and put a while loop at the end
//Create a callback for myRestService
myRestService.onreadystatechange = function()
{
if (myRestService.readyState == 4)
{
if(myRestService.status == 200)
{
// Retrieve the json object and work on it
var obj = JSON.parse(myRestService.responseText);
for(var i=0;i<obj.length;i++)
{
var item = obj[i];
$(“#restDataResults”).append(
‘<tr><td>’+ item.value1 + ‘</td>’ +
‘<td>’ + item.value2 + ‘</td>’ +
‘</tr>’);
}
done = true;
}
else if(myRestService.status == 404)
{
alert(‘Error occurred:’ + myRestService.responseText);
}else{
alert(“No resposne–Error”);
}
}
};
tempresults = myRestService.send(null);
while(done == false){
//wait here
}
In this case you will see a warning pop up in Firefox
A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.
Option B : false changes to true and we make synchronous calls
myRestService.open(“GET”, serviceUrl, true);
Now this works out well in IE but FF does not accept it.
Why it does not work ? Because we are still using the callback mechanism to get back the results
If we change it to regular method call , it will return results
Here is the code
<html>
<head>
<script type=”text/javascript” charset=”utf-8″ src=”json2.js”></script>
<script type=”text/javascript” charset=”utf-8″ src=”jquery-1.4.4.min.js”></script>
<script>
var restDataResults;
var done = false;
function callMyFirstRestService()
{
var myRestService = null;
if (window.XMLHttpRequest) //for mozilla
{
myRestService = new XMLHttpRequest();
if ( typeof myRestService.overrideMimeType != ‘undefined’)
myRestService.overrideMimeType(‘application/json’);
}
else if (window.ActiveXObject) //for IE
{
myRestService = new ActiveXObject(“Microsoft.XMLHTTP”);
}
//This is the url/ restApp is the web app deployed on tomcat.
var serviceUrl = “http://127.0.0.1:8080/restApp/webresources/paramater/1440″;
myRestService.open(“GET”, serviceUrl, false);
//synchronous calls
tempresults = myRestService.send();
var obj = JSON.parse(myRestService.responseText);
}
</script>
</head>
<body>
<h2>My First Rest Service</h2>
<p>My rest Service:
<input type=”button” id=”submitlookup” name=”submitlookup” value=”My First rest Service” onClick=”javascript:callMyFirstRestService();”/>
</p>
<div id=”divRestData” title=”My rest data”>
<table border=”1″>
<thead><tr>
<td width=’70’>Column A Heading</td>
<td width=’100′>Column B Heading</td>
</tr></thead>
<tbody id=’restDataResults’>
</tbody>
</table>
</div>
</body>
</html>
Hope you would have find this helpful.