js主要代码:
function test(){
var url = "${pageContext.request.contextPath}/elecRoleAction!edit.action";
$.ajax({
url:url,
type:'post', //数据发送方式
dataType:'json', //接受数据格式 (这里有很多,常用的有html,xml,js,json)
data:, //要传递的数据
error: function(){ //失败
alert('Error loading document');
},
success: function(msg){ //成功
alert("服务器返回数据如下:");
for(var i = 0;i<msg.length;i++){
var mm = msg[i];
alert("userName is:"+mm.userName+" password is:"+mm.pasd);
}
}
});
}
java主要代码:
public class ElecRoleAction extends BaseAction {
public void edit() throws IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 需要导入gson包;import com.google.gson.JsonObject;
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("userName", "hello");
jsonObj.addProperty("pasd", "12345");
JsonObject jsonObj2 = new JsonObject();
jsonObj2.addProperty("userName", "ajax");
jsonObj2.addProperty("pasd", "678910");
List<JsonObject> jsonList = new ArrayList<JsonObject>();
jsonList.add(jsonObj);
jsonList.add(jsonObj2);
String str = jsonList.toString();
out.println(str);
}
}
public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
protected HttpServletRequest request = null;
protected HttpServletResponse response = null;
//// 实现ServletResponseAware接口的setServletResponse方法,用于获得request对象
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
// 实现ServletResponseAware接口的setServletResponse方法,用于获得response对象
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。