将Struts2操作中的字符串返回给jQuery

时间:2015-01-29 18:03:28

标签: java jquery ajax struts2

我使用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。我怎么能做到这一点?

1 个答案:

答案 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类型推断它。)