ajax使用json
json是什么什么的废话不说了,去百度吧。我这里介绍一下我为何要使用json。我使用ajax响应返回值时,项目中需求要返回多个值,不能只返回一个值。这时候就想起来用到json了。这可能只是json的一个用途吧。以后的用途需要的时候会再介绍的。
我们使用json需要导入的包有很多
json-lib-2.3-jdk15.jar commons-beanutils-1.7.0.jar commons-httpclient-3.1.jar commons-lang-2.3.jar commons-logging-1.0.4.jar commons-collections-3.1.jar ezmorph-1.0.3.jar
找起来也很麻烦。我这有一个整合好的
http://pan.baidu.com/s/1o7qhWWa
加入jar包后。来介绍一个代码
服务端代码
res.setContentType("text/html;charset=utf-8");
res.setHeader("Cache-Control", "no-cache");
PrintWriter pw=res.getWriter(); //防止中文乱码
if(dimensionService.isexist()!=null){ //项目逻辑
Map<String,String> items=new HashMap<String, String>(); //定义键值对
Dimension dimension=dimensionService.isexist(); //项目逻辑
dimensionService.delete(dimension); //项目逻辑
String studentName=studentService.getStudnetById(dimension.getStudentId()).getName(); //项目逻辑
String photoAddress=studentService.getStudnetById(dimension.getStudentId()).getPhotoAddress(); //项目逻辑
items.put("studentName", studentName); //这里将值传入items,我这里传入了两个值
items.put("photoAddress", photoAddress);
JSONObject jo=JSONObject.fromObject(items); //定义jsonObject
pw.write(jo.toString());
}else{
pw.write("falses");
}
pw.flush();
pw.close();
下面是客户端代码
$.ajax({ type:"get", async:true, cache:false, url:"student.do", dataType:"json", //必写 data: {method:"reg3"}, contentType: "application/x-www-form-urlencoded; charset=utf-8", //防止提交中文乱码 success:function(msg){ try{ if(msg!=="falses"){ var photoAddress="member-show.jsp?photoAddress="+msg.photoAddress; layer_show(msg.studentName,photoAddress,'360','423'); /* window.location.href='success.jsp'; */ } }catch(e){ alert('服务器繁忙!请稍后再试!'); } }
这样就实现了ajax使用json了。

浙公网安备 33010602011771号