Return string from Struts2 action in jQuery

I invoke the Struts2 action using jQuery Ajax as follows:

 $.ajax ({  
        url: 'callAction.action',
        type: 'POST',
        data: data,
        dataType: 'string',
        success: function (data) {
           console.log("Success");
        }
});

And in response, it should return the string back to jQuery.

private String result;
//getters and setters

public String call()
{
   //some code
   result= "some string";

   return SUCCESS;
}

I want to extract resultfrom a function into a Struts action in jQuery. How can I make this possible?

+4
source share
1 answer

You can use the streamresult to get only the row from the action.

Configure the action to use the result streamwith contentTypeset to text/plain(or don’t use it at all contentType, because it is text/plainset by default).

<action name="callAction" method="call">
    <result type="stream">
        <param name="contentType">text/plain</param>
    </result>
</action>

InputStream getter/setter String .

private InputStream inputStream;
// getter/setter

public String callAction() {
    inputStream = new ByteArrayInputStream(
            "some string".getBytes(StandardCharsets.UTF_8));
    return SUCCESS;
}

ajax:

$.ajax ({  
    url: '<s:url action="callAction"/>',
    type: 'POST',
    dataType: 'text',
    success: function (data) {
        console.log(data);
    }
});

. <s:url> url-s dataType string, text (jQuery MIME- ).

+2

All Articles