从Struts2动作返回一个字符串到jQuery
我使用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。 我怎么能做到这一点?
您可以使用stream
结果从操作中获取一个String。
配置您的操作以使用contentType
设置为text/plain
stream
结果(或者根本不使用contentType
,因为默认情况下设置text/plain
)。
text/plain
在您的操作中,使用getter / setter创建InputStream
字段,并在您的操作方法中将String转换为输入流。
private InputStream inputStream; // getter/setter public String callAction() { inputStream = new ByteArrayInputStream( "some string".getBytes(StandardCharsets.UTF_8)); return SUCCESS; }
然后你可以像这样执行ajax请求:
$.ajax ({ url: ' ', type: 'POST', dataType: 'text', success: function (data) { console.log(data); } });
注意:最好使用
标签来构造url-s,并且没有像string
这样的dataType
,使用text
或根本不设置它(jQuery会尝试根据MIME类型推断它的回应)。