我使用 Ajax 从 Struts 2 获取成功响应,但最终给出了错误函数的响应并解析 Ajax 中解析 JSON 的错误。
下面是我的代码。
操作类 - PropertyTesting.java
import java.io.IOException;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class PropertyTesting extends ActionSupport
{
public String execute()
{
JSONObject obj = new JSONObject();
obj.put("Name", "PersonName");
obj.put("ID", "PersonID");
try {
ServletActionContext.getResponse().getWriter().write(obj.toJSONString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
}
JSP 页面 - PropertyTesting.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Property Testing</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
function invokeAjax()
{
$.ajax(
{
type:"POST",
url:"PropertyTesting",
dataType:"json",
success: function(responseText)
{
console.log(responseText);
},
error: function(errorResponse)
{
console.log(errorResponse);
}
});
}
</script>
</head>
<body>
<button type="button" onclick="invokeAjax()" >Submit</button>
</body>
</html>
Struts.xml
<struts>
<constant name="struts.devMode" value="true"/>
<package name="WebTesting" extends="json-default">
<action name="PropertyTesting" class="org.testing.PropertyTesting" >
<result type="json"></result>
</action>
</package>
</struts>
而且,如果我使用 Servlet 做同样的事情,它会给我使用 Struts 的确切结果,但只会出现此类问题。
JSONObject
是一种问题。默认情况下,它会序列化操作。由于您没有要序列化的属性,因此您应该创建一个。
Struts2 中的操作不是单例,因此您不应该害怕创建属性。
public class PropertyTesting extends ActionSupport
{
Map obj;
public Map getJSON(){
return obj;
}
public String execute()
{
obj = new HashMap();
obj.put("Name", "PersonName");
obj.put("ID", "PersonID");
return SUCCESS;
}
}