我使用jQuery Ajax调用Struts2操作,如下所示:
$.ajax ({
url: 'callAction.action',
type: 'POST',
data: data,
dataType: 'string',
success: function (data) {
console.log("Success");
}
});
作为回应,它必须将字符串返回给jQuery。
private String result;
//getters and setters
public String call()
{
//some code
result= "some string";
return SUCCESS;
}
我想从Struts动作中的函数中检索result
到jQuery。我怎么能做到这一点?
答案 0 :(得分:2)
您可以使用stream
结果从动作中获取一个字符串。
将您的操作配置为使用stream
结果,contentType
设置为text/plain
(或者根本不使用contentType
,因为text/plain
是<action name="callAction" method="call">
<result type="stream">
<param name="contentType">text/plain</param>
</result>
</action>
默认设置)。
InputStream
在您的操作中,使用getter / setter创建private InputStream inputStream;
// getter/setter
public String callAction() {
inputStream = new ByteArrayInputStream(
"some string".getBytes(StandardCharsets.UTF_8));
return SUCCESS;
}
字段,并在您的操作方法中将String转换为输入流。
$.ajax ({
url: '<s:url action="callAction"/>',
type: 'POST',
dataType: 'text',
success: function (data) {
console.log(data);
}
});
然后你可以像这样执行ajax请求:
<s:url>
注意:最好使用string
代码构建url-s,而text
不是{{1}},使用{{1}}或者不要&# 39; t设置它(jQuery将尝试根据响应的MIME类型推断它。)