Json就是浏览器和服务器之间交换数据的一种轻量级对象
$(function() { var person = { "name" : "张三", "age" : 21, "wife" : "李四" }; $("#msg").append("姓名:" + person.name+"<br/>").append("年龄:" + person.age+"<br/>") .append("老婆:" + person.wife+"<br/>"); })二、一个小例子
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>json测试</title><script type="text/Javascript" src="js/jquery-1.8.2.js"></script><script type="text/javascript" src="js/jsonDemo.js"></script><style type="text/CSS">td {border: 1px solid blue;width:100px;}</style></head><body><div id="msg"></div><div id="msg2"></div><div id="msg3"></div><input id="btn" type="button" value="JSON与字符串转换" /><br/><input id="btn2" type="button" value="字符串与JSON转换" /></body></html>
$(function() { // json对象 var person = { "name" : "张三", "age" : 21, "wife" : "李四" }; $("#msg").append("姓名:" + person.name + "<br/>").append("年龄:" + person.age + "<br/>").append("老婆:" + person.wife + "<br/>"); // 数组 var arr1 = ["广东", "广西", "湖南", "湖北", "江西"] // 使用循环遍历 for (var i = 0; i < arr1.length; i++) { $("#msg2").append(arr1[i] + " "); } // 对象数组 var users = [{ "name" : "张三", "pwd" : "123qwe", "age" : 21 }, { "name" : "李四", "pwd" : "asdf", "age" : 22 }, { "name" : "王五", "pwd" : "fsde", "age" : 23 }, { "name" : "赵六", "pwd" : "zcxe", "age" : 24 }]; $("#msg3").append("<table>"); for (var i = 0; i < users.length; i++) { $("#msg3").append("<tr>").append("<td>" + users[i].name + "</td>").append("<td>" + users[i].pwd + "</td>").append("<td>" + users[i].age + "</td>").append("</tr>"); } $("#msg3").append("</table>"); // json和字符串转换 $("#btn").bind("click",function(){ alert(JSON.stringify(users)) alert(typeof JSON.stringify(users)) }) //将字符串转换为对象 var str='{"name":"张三丰","pwd":"qwer","age":123}' $("#btn2").bind("click",function(){ alert(JSON.parse(str).name); //显示类型为string alert(typeof JSON.parse(str).name) alert(JSON.parse(str).pwd); alert(typeof JSON.parse(str).pwd) alert(JSON.parse(str).age); //显示类型为number alert(typeof JSON.parse(str).age) }) })三、服务器端设置和客户端使用Ajax请求
<param name="excludePRoperties" >不包含的元素 </param><param name="includeProperties" >包含的元素 </param> <param name="root"> person.job 字段或者对象 </param>3.1、Ajax实现取重服务器端的数据
package com.pb.web.action;import com.opensymphony.xwork2.ActionSupport;public class DataAction extends ActionSupport { private String name; private String pwd; private Integer age; public String getData(){ name="张三丰"; pwd="太极宗师108"; age=108; return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="json-default"> <action name="getData" class="com.pb.web.action.DataAction" method="getData"> <result type="json"> <!--默认返回Action中全部数据 param可以指定下要传的元素 --> <param name="includeProperties"> name,pwd,age </param> </result> </action> </package></struts>
javascript
$(function() { $("#btn").click(function() { $.ajax({ url : "getData", type : "post", data : null, dataType : "json", success : function(data) { $("#msg").html(""); $("#msg").append("姓名:" + data.name + "<br/>") .append("密码:" + data.pwd + "<br/>") .append("年龄:" + data.age + "<br/>") }, error : function() { $("#msg").html(""); $("#msg").html("获取数据失败"); } }); }); });
页面
<input type="button" id="btn" value="Ajax获取Json" /><div id="msg"></div>四、返回对象和集合时
package com.pb.web.action;import java.util.ArrayList;import java.util.List;import com.opensymphony.xwork2.ActionSupport;import com.pb.entity.User;public class DataAction extends ActionSupport { private String name; private String pwd; private Integer age; private User user; private List<User> users; public String getData(){ name="张三丰"; pwd="太极宗师108"; age=108; return SUCCESS; } public String getUserString(){ user=new User(1, "乔丹", "123", 40); return SUCCESS; } public String getUsersstring(){ users=new ArrayList<User>(); users.add(new User(1, "乔丹", "123", 40)); users.add(new User(2, "科比", "123", 36)); users.add(new User(3, "C罗", "123", 25)); return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; }}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="json-default"> <action name="getData" class="com.pb.web.action.DataAction" method="getData"> <result type="json"> 默认返回Action中全部数据 param可以指定下要传的元素 <param name="includeProperties"> name,pwd,age </param> </result> </action> <action name="getUser" class="com.pb.web.action.DataAction" method="getUserString"> <result type="json"><!-- 默认返回Action中全部数据 param可以指定下要传的元素 <param name="root"> ajax接收直接data.属性就可以 user </param> --> <param name="includeProperties">user.*</param> <!-- 使用 对象.*时接收时ajax要用 date.user.属性才可以--> </result> </action> <action name="getUsers" class="com.pb.web.action.DataAction" method="getUsersString"> <result type="json"> <!-- 默认返回Action中全部数据 param可以指定下要传的元素 --> <!-- --><!-- ajax接收直接 data.length遍历时取值使用data[i].属性就可以 --><!-- <param name="root"> users </param> --> <param name="includeProperties">users.*</param> <!-- 使用 对象.*时接收时ajax要用 date.users.length 取值时使用date.users[i].属性才可以 --> </result> </action> </package></struts>
javascript
$(function() { $("#btn").click(function() { $.ajax({ url : "getData", type : "post", data : null, dataType : "json", success : function(data) { $("#msg").html(""); $("#msg").append("姓名:" + data.name + "<br/>") .append("密码:" + data.pwd + "<br/>") .append("年龄:" + data.age + "<br/>") }, error : function() { $("#msg").html(""); $("#msg").html("获取数据失败"); } }); }); // 获取用户对象 $("#btn2").click(function() { $.ajax({ url : "getUser", type : "post", data : null, dataType : "json", success : function(data) { $("#msg2").html(""); $("#msg2").append("ID:" + data.user.id + "<br/>") .append("姓名:" + data.user.username + "<br/>") .append("密码:" + data.user.passWord + "<br/>") .append("年龄:" + data.user.age + "<br/>") }, error : function() { $("#msg2").html(""); $("#msg2").html("获取数据失败"); } }); }); // 获取对象集合 $("#btn3").click(function() { $.ajax({ url : "getUsers", type : "post", data : null, dataType : "json", success : function(data) { $("#msg3").html(""); $("#msg3").append("<tabel>"); for (var i = 0; i < data.users.length; i++) { $("#msg3") .append("<tr>") .append("<td>" + data.users[i].id + "</td>") .append("<td>" + data.users[i].username + "</td>") .append("<td>" + data.users[i].password + "</td>") .append("<td>" + data.users[i].age + "</td>").append("</tr>"); } $("#msg3").append("<tabel>"); }, error : function() { $("#msg3").html(""); $("#msg3").html("获取数据失败"); } }); });});五、无刷新页页登录和注销
package com.pb.entity;/* * 用户实体类 */public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.pb.web.action;import java.util.Map;import org.apache.struts2.interceptor.sessionAware;import com.opensymphony.xwork2.ActionSupport;import com.pb.entity.User;public class UserAction extends ActionSupport implements SessionAware { private User user; private Map<String, Object> session; private boolean flag; //登录的验证方法 public String login(){ if(user.getUsername().equals("accp")&&user.getPassword().equals("accp")){ //如果用户名和密码都正确,将这个用户放入Session中 session.put("u", user); flag=true; }else{ flag=false; } return SUCCESS; } /* * 退出 */ public String logout(){ session.remove("user"); return SUCCESS; } //实现sesssionAware接口的方法 @Override public void setSession(Map<String, Object> session) { this.session=session; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Map<String, Object> getSession() { return session; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; }}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="json-default"> <action name="login" class="com.pb.web.action.UserAction" method="login"> <result type="json"> <param name="includeProperties"> flag,user.* </param> </result> </action> <action name="logout" class="com.pb.web.action.UserAction" method="logout"> <result type="json"> <param name="includeProperties"> null </param> </result> </action> </package></struts>
页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登录页面</title><script type="text/javascript" src="js/jquery-1.8.2.js"></script><script type="text/javascript" src="js/loginDemo.js"></script></head><body><div id="loginDiv">用户名:<input type="text" name="name" /><br/>密码:<input type="password" name="password"/><br/><input type="button" value="登录" id="loginbtn" /><span id="msg"></span></div></body></html>
js
/** * 登录页面js */$(function() { $("#loginbtn").click(function() { var params = { "user.username" : $("input[name='name']").val(), "user.password" : $("input[name='password']").val() } $.ajax({ url : "login.action", type : "post", data : params, dataType : "json", success : function(data) { // alert(data.flag); if (data.flag == true) { $("#loginDiv") .html("") .append("欢迎您!") .append(data.user.username) .append("<input id='logoutbtn' type='button' value='注销' />") } else { $("#msg").html("") $("#msg").append("用户名或者密码错误 !").css( "color", "#FF0000") } }, error : function() { $("#msg").html("") $("#msg").append("登录异常!").css("color", "#FF0000"); } }); }); $("#logoutbtn").live("click",function(){ $.ajax({ url:"logout", type:"post", dataType:"json", success:function(data){ //alert(JSON.stringify(data)); $("#loginDiv").html(""); $("#loginDiv").append('用户名:<input type="text" id="username" value="">密码:<input type="password" id="password" value=""><input type="button" value="登录" id="btn"><span id="msg"></span>'); }, error:function(){ alert("ajax请求失败"); } }); }); });
新闻热点
疑难解答