Teddy, it sounds like the focus of your question is how to make an ajax call to a Struts action and then how to use the response. I will try to point you in the right direction. You didn't mention which version of Struts you are using, but I am going to assume Struts2. The ajax framework that I use is dojo.
Let's say, with ajax (using the dojo framework), you wanted to post a staffId, get back the associated staff name from an action named staff. and then populate a td with id "staffNameDisplay". Your html might look something like this:
Staff Id: <input type="text" name="staffNum" id="staffNum" value="5" />
<input type="button" id="searchButton" value="Search" onClick="postStaffId()" />
....
<td id="staffNameDisplay"></td>
.... And your javascript function might be like this:
function postStaffId() {
var staffNum = document.getElementById("staffNum").value;
dojo.xhrPost( {
url: "staff",
sync: false,
content: {
staffId: staffNum
},
handleAs: "json",
// The LOAD function will be called on a successful response.
load: function(response, ioArgs) {
dojo.byId("staffNameDisplay").innerHTML = "The associated staff name is " + response.staffName;
},
// The ERROR function will be called in an error case.
error: function(response, ioArgs) {
console.error("HTTP status code: ", ioArgs.xhr.status);
return response;
}
});
}
The url property must be the name of your action (e.g. staff) and the handleAs refers to the format in which you are expecting the response (e.g. json). Content are name/value pairs of variables you are setting in the Action (in this case I am setting the variable staffId).
If you are using dojo to make the ajax post, you must reference the dojo javascript file at the top of the javascript code with:
<script type="text/javascript" src="js/dojo/dojo.js"></script>
Obviosuly, you need to have the dojo.js file in the js/dojo directory of your web application.
To make your action named staff be returned in json format,
you should extend the json-default package and specify a return type of json in your struts.xml:
<package name="ajax" extends="json-default" >
<action name="staff" method="JSONStaff" class="myclass.actions.StaffAction" >
<result name="success" type="json" />
</action>
</package>
You can see from the above declaration that a method called JSONStaff will be executed when the staff action is invoked.
In your JSONStaff method you would set the value of variables such as the staffName (perhaps via a database lookup using the staffId)
and return SUCCESS.
When your Action is returned as type json, unless you explicitly include or exclude properties, all of your Action variables will be accessible in the response using dot syntax (e.g. response.staffName)
To enable you to return your Action as a JSONObject, you need to install the following 2 jars:
json-lib-2.1-jdk15
struts2-json-plugin-2.3.1.2
I hope this helps get you on track.