分享

ajax 调用action方法 ,返回一个对象的list列表,调用成功后循环遍历

 藏经阁_苍穹 2015-10-07
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;
}

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多