将Struts2操作中的字符串返回给jQuery [英] Return a string from Struts2 action to jQuery
问题描述
我使用jQuery Ajax调用Struts2操作,如下所示:
I call a Struts2 action using jQuery Ajax like the following:
$.ajax ({
url: 'callAction.action',
type: 'POST',
data: data,
dataType: 'string',
success: function (data) {
console.log("Success");
}
});
作为回应,它必须将字符串返回给jQuery。
And in response, it has to return a string back to jQuery.
private String result;
//getters and setters
public String call()
{
//some code
result= "some string";
return SUCCESS;
}
我想检索结果
从Struts动作中的函数到jQuery。我怎么能做到这一点?
I want to retrieve the result
from the function in the Struts action to jQuery. How would I make this possible?
推荐答案
您可以使用 stream
结果只能从动作中获取一个字符串。
You can use stream
result to get just a String from the action.
将您的操作配置为使用 stream
结果, contentType
设置为 text / plain
(或者根本不使用 contentType
,因为默认设置 text / plain
。
Configure your action to use stream
result with contentType
set to text/plain
(or don't use contentType
at all, because text/plain
is set by default).
<action name="callAction" method="call">
<result type="stream">
<param name="contentType">text/plain</param>
</result>
</action>
在您的操作中,使用getter创建 InputStream
字段/ setter和你的action方法将String转换为输入流。
In your action create InputStream
field with getter/setter and in your action method convert String to the input stream.
private InputStream inputStream;
// getter/setter
public String callAction() {
inputStream = new ByteArrayInputStream(
"some string".getBytes(StandardCharsets.UTF_8));
return SUCCESS;
}
然后你可以像这样执行ajax请求:
Then you can execute ajax request like that:
$.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类型推断它)。
Note: it is better to use <s:url>
tag to construct url-s and there isn't such dataType
as string
, use text
or don't set it at all (jQuery will try to infer it based on the MIME type of the response).
这篇关于将Struts2操作中的字符串返回给jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!