實現ajax後臺與前臺的相互傳值與(地址需轉碼後傳)
阿新 • • 發佈:2018-12-25
首先需要導包
commons-beanutils-1.7.0.jar
commons-collections-3.2.1.jar
commons-lang-2.3.jar
commons-lang3-3.1.jar
commons-logging-1.0.4.jar
後臺接受前臺需用set get方法
這是action public class Action extends ActionSupport { private long num; private int type; String documentType; public long getNum() { return num; } public void setNum(long num) { this.num = num; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String show() throws IOException { Gson sGson = new Gson(); JSONArray jsonArray = new JSONArray() ; for(int i=0;i<2;i++){ Object[] objects = new Object[1]; objects[0]=1; objects[1]=URLEncoder.encode("https://www.baidu.com/", "utf-8");//進行轉碼 } jsonArray.add(objects); String json = sGson.toJson(jsonArray); ServletActionContext.getResponse().setContentType("text/html;charset=utf-8"); ServletActionContext.getResponse().getWriter().write(json); System.out.println(num); System.out.println(type); return null; } }
這是js前臺程式碼
var params= $.param({ 'num' : 123, 'type' : 456, }, true); $.ajax({ type : 'POST', url : 'Action ', async:true, data :params, success : function(data) { data =JSON.parse(data); for ( var x in data) { data[x][1]=decodeURI(data[x][1], "utf-8");//解碼 console.log(data); } }, error : function() { console.log("errpr"); } });
struts程式碼
<action name="Action " class="Action " method="show">
</action>