Servlet的代码:
public void doPost(HttpServletRequest req,HttpServletResponse resp){
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
String str = "[{pid:1,pname:'吉林省'},{pid:2,pname:'辽宁省'},{pid:3,pname:'山东省'}]";
out.print(str);
//疑惑:JSON的key是否一定要用双引号?
}
window.onload = function(){
document.getElementById("checkusername").onclick = function(){
var username = document.getElementById("username").value;
//alert(username);
//1
var xmlReq = ajaxFunction();
//2
xmlReq.onreadystatechange = function(){
if(xmlReq.readyState==4){
if(xmlReq.status==200||xmlReq.status==304){
var data = xmlReq.responseText;
//使用eval()方法把JSON字符串转成对象
var dataObj = eval("("+data+")");
for (var i=0;i<dataObj.length ;i++ ){
alert(dataObj[i].pid+"=="+dataObj[i].pname);
}
}
}
}
//3
xmlReq.open("post","../registerServlet",true);
xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4
xmlReq.send("username="+username);
}
}
例子:
Servlet的代码:
public void doPost(HttpServletRequest req,HttpServletResponse resp){
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
List<Province> list = new ArrayList<Province>();
Province p1 = new Province(1,"吉林省");
Province p2 = new Province(2,"辽宁省");
Province p3 = new Province(3,"山东省");
list.add(p1);
list.add(p2);
list.add(p3);
JsonConfig config = new JsonConfig();
//过滤list集合中存放的Province这个对象的pid属性不生成json
config.setExcludes(new String[]{"pid"});//把pid屏蔽掉
JSONArray jsonArray = JSONArray.fromObject(list,config);
out.print(jsonArray.toString());
/************以上是list,下面的是一个对象**********************/
Province p = new Province(1,"吉林省");
JsonConfig config1 = new JsonConfig();
config.setExcludes(new String[]{"pid"});
JSONObject jsonObject = JSONObject.fromObject(p,config1);
System.out.println(jsonObject.toString());
}