Possible Duplicate:
How use $.ajax() method in struts2
只是,
1. sombody可以告诉我如何通过jquery ajax调用struts动作吗(不是struts jquery插件)
2.如何获取结果以及如何将html输出(结果)正确发送到目标div?
3.我们应该在struts配置中更改结果类型吗?
4.ajax内容加载后如何运行javascript?
5.以及其他我应该知道的有关jquery ajax和javascript运行的struts动作的其他信息。
请有人可以分享有关此答案或干净答案的最佳参考。
最佳答案
尽管您可以在网上轻松找到这些信息的零碎部分。让我们放在同一页上。
回答1 ::包括JQuery的js文件并编写您的ajax调用。
$(document).ready(function() {
$.ajax({
type: "POST", //Default is GET
cache : false,
data: sendingData, //Data you need to send if in JSON format
dataType: 'json', //If json is required
contentType: 'application/json; charset=utf-8',
url: "MYACTIONNAME.action", //URL you need to pass
success: function(value) {
alert(value.properties);
},
error: function (xhr, ajaxOptions, thrownError) {
$(".errors").html("Please Try Again");
//console.log(xhr.status + thrownError);
}
});
$(document).ready(function() {
$("#div").load("MYActionName.action"); //can do that through $.ajax also
});
$("#divToReplaceWithNewOne").hide().load('MyActionName.action #newDivWhichWillbeFilled').fadeIn(1000); //with animation
<action name="MYActionName" class="MYActionNameBean" method ="execute">
<result name="success" type="dispatcher">
<param name="location">/jsp/MyNewPage.jsp</param>
</result>
</action>
<action name="MYActionName" class="MYActionNameBean" method="execute">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
public String execution() throws Exception {
try{
PrintWriter outWriter = null;
StringBuffer sbf = new StringBuffer("");
HttpServletResponse httpResponse = ServletActionContext.getResponse();
try {
outWriter = httpResponse.getWriter();
sbf.append("String to be sent to View");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(outWriter!=null){
httpResponse.setContentType("text/html");
outWriter.println(sbf.toString());
outWriter.flush();
outWriter.close();
}
}
}catch (Exception e) {
throw new MyOwnException(e);
}
return null;
}
<action name="MYActionName" class="MYActionNameBean" method="execute">
<result type="json"></result>
</action>
<action name="DownloadPdf" class="PrintPdfActionBean" method="executeViewPdf">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment; filename="${fileName}.pdf"</param> //filename is variable in action class
<param name="bufferSize">4096</param>
</result>
</action>
success: function(value) {
var respStat = data.status;
var errorStat = data.errorsMessages;
if(respStat =="success"){
responseMsg.removeClass().addClass('successMessage').html("Your changes have been saved successfully.").fadeOut(4000);
}
else{
responseMsg.removeClass().addClass('errorMessage').html(errorStat[0]).show();
}
},
关于javascript - struts2 Action 和jquery ajax ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12480651/