ajax 调用后端传递的map类型时,ajax的接收数据类型是json类型,那就需要把后端map转成json才能接收,
这里用到阿里巴巴的fastjson或者json-lib(比较老了,建议不用)
Map转成json格式
Map<String,Object> map = new HashMap<String,Object>();
map.put("users", users);
map.put("u", u);
1.转成JSONArray类型
JSONArray json = JSONArray.fromObject(map);
System.out.println(json.toString());//
[{"users":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"1234","username":"lhl"}}]
response.getWriter().print(json.toString);
js中取数据:alert(data[0].users[0].username);
2.转成JSONObject类型
JSONObject json = JSONObject.fromObject(map);
System.out.println(json);//
{"user":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"1234","username":"lhl"}}
response.getWriter().print(json);
js中取数据:alert(data.user[0].username);
这里会出现fromObject(Map<String,Object>) is undefined for the type JSONObject错误
原因就是因为引入包的问题
org.json.JSONObject:
- 1
net.sf.json.JSONObject:
- 1
net.sf.json.jsonobject 没有 new JSONObject(String)的构造方法
当使用Ajax调用后端传递的Map类型数据时,需要将Map转换为JSON格式。可以使用阿里巴巴的Fastjson或较旧的json-lib库进行转换。转换后,可以通过JSONArray或JSONObject在JavaScript中访问数据。但需要注意,不同库的JSONObject可能有不同的构造方法,如遇到'fromObject(Map<String,Object>) is undefined for the type JSONObject'错误,可能是因为导入了错误的JSON库。"
106729573,8187283,使用IDEA搭建Spring Boot + Mybatis CRUD应用,"['Java', 'Spring框架', 'Mybatis', 'Web开发', 'IDEA']
551

被折叠的 条评论
为什么被折叠?



