//②jsonStr转json对象方式二:
var jsonStr2 = '{"name" : "黄小邪", "age" : 23, "sex" : true}';
//注意:使用JSON.parse转换jsonStr必须保证jsonStr是标准格式的字符串
var jsonObj2 = JSON.parse(jsonStr2);
console.debug(jsonObj2);
1.5.JSON与Ajax实现二级联动实例
这里使用JSON字符串操作并向前台传输JSON格式的数据来展示JSON与Ajax之间的操作实现。
后台:
虚拟了两个省、市Domain并提供加载获取省、市的方法供Servlet向前台传输数据:
City.java:
/**
* 城市对象
*
*/
public class City {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public City() {
}
public City(Long id, String name) {
super();
this.id = id;
this.name = name;
}
/**
* 根据省份id查询省份中的城市!
*
* @return
*/
public static List getCityByProvinceId(Long id) {
List citys = new ArrayList();
if (id == 1) {
citys = Arrays.asList(
new City(1L,"成都"),
new City(2L,"南充"),
new City(3L,"绵阳"),
new City(4L,"遂林"),
new City(5L,"达州"),
new City(6L,"德阳"),
new City(7L,"乐山")
);
} else if (id == 2) {
citys = Arrays.asList(
new City(11L,"广州"),
new City(12L,"佛山"),
new City(13L,"东莞")
);
} else if (id == 3) {
citys = Arrays.asList(
new City(21L,"昆明"),
new City(22L,"玉溪"),
new City(23L,"丽江")
);
}
return citys;
}
}
Province.java:
public class Province {
private Long id;
private String name;
public Province(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Province() {
super();
}
public static List getAllProvince() {
List provinces = new ArrayList();
provinces.add(new Province(1L, "四川"));
provinces.add(new Province(2L, "广东"));
provinces.add(new Province(3L, "云南"));
return provinces;
}
}
提供一个CityProvinceServlet向Ajax提供请求地址:
@WebServlet("/loadData")
public class CityProvinceServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String cmd = req.getParameter("cmd");
String id = req.getParameter("id");
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/json;charset=UTF-8");
//加载省
if(cmd.equals("province")){
List provinceList = Province.getAllProvince();
resp.getWriter().print(JSONSerializer.toJSON(provinceList));
System.out.println("加载省!");
}
//加载市
else {
if(id != null && id != ""){
List cityList = City.getCityByProvinceId(Long.parseLong(id));
resp.getWriter().print(JSONSerializer.toJSON(cityList));
System.out.println("加载市!");
}
}
}
}