
[英]How to send JSON data via POST (Ajax) and receive JSON response from Struts 2 action
[英]How to call action class from ajax and receive the data back?
我需要上传用户的 excel 文件,如果 excel 文件具有“A”类型的用户,那么我需要显示一个弹出窗口,询问“您确定用户是“A”类型吗? 并转发它操作 class 读取并保存 excel 文件中的内容。 如果用户不是“A”类型,则无需显示弹出窗口,只需将其转发到操作 class。
Web 应用程序基于 Struts 1.2、java、jsp。
为了实现这一点,我在 JSP 中使用 ajax 调用。 它不会去 UploadUserCheckAction.java,而只会去 UploadUserAction.java。
如果我在这里遗漏了什么,有人可以帮我纠正我吗? 或者,如果有不同的方法可以实现这一点,请告诉我。
Struts-config.xml:
<action path="/uploadUser"
type="com.games.web.actions.admin.UploadUserAction"
name="uploadForm" scope="request" validate="false">
<forward name="uploaded" path="uploadedDone.Page" />
<forward name="upload" path="upload.Page" />
</action>
<action path="/uploadUserPreCheck"
type="com.games.web.actions.admin.UploadUserCheckAction"
name="uploadForm" scope="session" validate="false">
<forward name="back" path="/uploadSetUp.do" redirect="true"/>
</action>
上传.jsp:
<script src="<%=request.getContextPath() %>/pages/js/jquery-3.2.0.min.js"></script>
-------------rest of the code
<html:form action="/uploadUser" method="post" enctype="multipart/form-data">
<html:hidden property="id" value="${currentSession.id}"/>
<html:file property="theFile" styleId="uploadUser" />
<html:submit onclick="checkIfUser(uploadUser)" > </html:submit>
</html:form>
----------rest of the code
<script language="JavaScript">
function checkIfUser(uploadUser) {
$.ajax({
type : "POST", // define the type of HTTP verb we want to use (POST for our form)
url : "http://localhost:8080/xxx/admin/uploadUserPreCheck.do", // the url where we want to POST
data: {"theFile": uploadUser}, // our data object
dataType: "json" // what type of data do we expect back from the server
}).done(function(data){
var containsUser = data.hasUser;
if(containsUser == 1){
alert("Are you sure the user is type 'A'?");
}
}).error(function(errorData){
console.log("error while reading the excel file " + errorData);
});;
}
</script>
<noscript>
<p>JavaScript needs to be enabled for this function to work.</p>
</noscript>
上传UserCheckAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
FormFile myFile = myForm.getTheFile();
int hasUser = 0;
--process the file and see if user type exist
JSONObject jsonObject = new JSONObject("{\"hasUser\" : " + hasUser + "}");
request.setAttribute("data", jsonObject);
return mapping.findForward("back");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.