Reputation: 5952
I send an Ajax request to an Action
class and try to get the response from a Result
.
Here is my jQuery code:
$('#button').click(function(){
$.get('ajax.action','query="hi server:)")',function(x,r,s){
alert("server said :"+r+"-stat-"+s.status);
})
Here always the response is 'success' which not the expected response.
Here is my Action class's execute().
String response;
String query;
@Override
public String execute() throws Exception {
response=query+" - Struts added :";
setResponse(response);
return SUCCESS;
}
There a getters and setter for string response and query have been written(not showed here).
Here is my Result
class
public class AjaxResponse implements Result {
@Override
public void execute(ActionInvocation ai) throws Exception {
System.out.println("I am the Ajax Rsponse RESULT");// this is displayed in the console
PrintWriter out =
ServletActionContext.getResponse().getWriter();
try {
ServletActionContext.getResponse().setContentType("text/plain");
ValueStack valueStack = ai.getStack();
// Object resObj= valueStack.findValue("response");
out.print("hi I am server ...");
System.out.println("Response WROTE---");
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
System.out.println("Response Close "); // this is displayed in the console
}
}
}
Here is how I added my Result class to struts.xml
<result-types>
<result-type name="ajaxResponse" class="com.app.ajax.AjaxResponse" />
</result-types>
Here is how I declared the action
<action name="ajax" class="com.app.action.AjaxSupport">
<result type="ajaxResponse"/>
</action>
The alert always gives only SUCCESS , not the expected result 'hi I am server ...' .
The console displays the Result class's prints-("I am the Ajax Response RESULT","Response WROTE---","Response Close") I used a separate Result class for loose couple the task and do the business logic inside the action class.
Please any one let me know where my problem is ?
Upvotes: 1
Views: 911
Reputation: 5952
Problem is in not in Struts but where I check the result whether it s right or wrong.
$.get('ajax.action', 'query="hi server")', function(x, r, s) {
alert("server said: " + r + "-stat-" + s.status);
According to this alert, the output is:
server said: success-stat-200
Problem was seeing this success . confused with callback function's parameters.
Here 'r'
is status of the response (I'd thought the response), s is xmlHttpRequest
object.
I had to check not r
, but x
which is real expected value. Printing x's value, the real value of what the server sent appeared.
Upvotes: 1