1. 注意:
- 首先要导jq的包
- json对象可以用 . 来调用key
- java只能给前端传页面,或者打印的内容
- String jsonstr = json.toJSONString(resultJSON); //将对象转为JSON对象
Json格式和参数解释:
<script src="js/jquery-1.10.2.min.js"></script> //导包
$(function (){$("button").click(function (){$.ajax({url:"/indexServlet",//请求路径servlet,如果一直拼会麻烦(即使是post也可以拼)type:"get",//默认是getasync:"true",//布尔值,请求是否异步处理,默认异步,false是同步data:{uname:"123",upwd:"123"},//请求数据dataType:"json",//返回值类型success:function (res) {$("h1").text(res.msg);msg1=res.msg;} ,error: function (code, msg) {// 请求失败后的回调函数console.log("Error Code: " + code); // 输出错误代码console.log("Error Message: " + msg); // 输出错误信息}});});});
1.实现前端与java通信:
使用get,通过?把参数传递到后端,后端用getParameter接收
这里的res是返回值,通过out.println(msg);把参数传递给json
后端:通过 PrintWriter
将消息发送到前端。
<body>
<h1>未登录</h1>
<button>ajax</button>
<script src="js/jquery-1.10.2.min.js"></script>
<script>$(function (){$("button").click(function (){$.ajax({url:"/indexServlet?name=111",//请求路径servlettype:"get",success:function (res) {$("h1").text(res);}})});});
</script>
</body>
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setCharacterEncoding("utf-8");String name = req.getParameter("name");System.out.println(name);String msg="登陆成功";PrintWriter out = resp.getWriter();out.println(msg);}
2.ajax是异步的
这里的alert弹出的值是空白的
这里的1和2是同时进行的,这种就叫异步
所以当alert(msg)时,ajax还没有返回值,所以就导致弹出的是空白
<h1>未登录</h1>
<button>ajax</button>
<script src="js/jquery-1.10.2.min.js"></script>
<script>$(function (){var msg="";$("button").click(function (){$.ajax({url:"/indexServlet?name=111",//请求路径servlettype:"get",success:function (res) {$("h1").text(res);msg=res;}})});alert(msg);});
</script>
3.将String转为json
像这样使用String j = "{\"code\":200,\"msg\":\"张三\"}";来传递json对象,太麻烦了,所以下面有阿里巴巴的包可以简单一些
dataType:"json",//返回值类型
PrintWriter out = resp.getWriter();String id = req.getParameter("id");String pwd = req.getParameter("pwd");System.out.println(id+pwd);if (id.equals("123")&&pwd.equals("123")){String j = "{\"code\":200,\"msg\":\"张三\"}";out.println(j);}else {out.println("登陆失败");}
但是这样是String类型的,我们需要转成json类型的
需要使用fastjson-1.2.13.jar这个包,导到lib里面
就像这样使用JSONObject来将字符串转为json对象传出去
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setCharacterEncoding("utf-8");resp.setContentType("application/json"); // 设置返回类型为 JSONPrintWriter out = resp.getWriter();String uname = req.getParameter("uname");String upwd = req.getParameter("upwd");JSONObject jsonObject = new JSONObject();//{}System.out.println("===="+uname+upwd);if (uname.equals("123")&&upwd.equals("123")){jsonObject.put("code",200);//{code:200}jsonObject.put("msg","登陆成功");//{code:200,msg:”登陆成功“}}else {jsonObject.put("code",400);jsonObject.put("msg","登陆失败");//{code:200,msg:”登陆失败“}}out.println(jsonObject);}
}
然后前端可以通过.来调用json对象的值
就像res.msg;
$(function (){$("button").click(function (){$.ajax({url:"/indexServlet",//请求路径servlet,如果一直拼会麻烦(即使是post也可以拼)type:"get",async:"false",//表示请求是否异步处理,默认异步,false是同步data:{uname:"123",upwd:"123"},dataType:"json",//返回值类型success:function (res) {$("h1").text(res.msg);}});});});
3.2.返回json数组
使用JSONArray jsonArray = new JSONArray();//[{},{},{}]
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setCharacterEncoding("utf-8");resp.setContentType("application/json"); // 设置返回类型为 JSONPrintWriter out = resp.getWriter();String uname = req.getParameter("uname");String upwd = req.getParameter("upwd");JSONObject jsonObject = new JSONObject();//{}JSONArray jsonArray = new JSONArray();//[{},{},{}]System.out.println("===="+uname+upwd);if (uname.equals("123")&&upwd.equals("123")){jsonObject.put("code",200);//{code:200}jsonObject.put("msg","登陆成功");//{code:200,msg:”登陆成功“}}else {jsonObject.put("code",400);jsonObject.put("msg","登陆失败");//{code:200,msg:”登陆失败“}}jsonArray.add(jsonObject);out.println(jsonArray);}
4.ResultJSON来统一格式化结果
它的目的是将服务器处理后的结果(如状态码、消息和数据)结构化并统一格式化为 JSON 形式,以便客户端(如前端 JavaScript)能够轻松地解析和处理这些数据。
(记得带上get set toString)
public class ResultJSON {private int code; // 状态码,通常 200 表示成功,其他表示失败或错误private String msg; // 响应消息private Object data; // 可能包含的附加数据(可以是任意类型)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setCharacterEncoding("utf-8");resp.setContentType("application/json"); // 设置返回类型为 JSONPrintWriter out = resp.getWriter();String uname = req.getParameter("uname");String upwd = req.getParameter("upwd");ResultJSON resultJSON = null;//这是我们自定义封装的类,目的是统一json对象System.out.println("===="+uname+upwd);if (uname.equals("123")&&upwd.equals("123")){resultJSON = new ResultJSON(200,"登陆成功");}else {resultJSON = new ResultJSON(400,"登陆失败");}JSONObject json = new JSONObject();//{}String jsonstr = json.toJSONString(resultJSON); //将对象转为JSON对象out.println(jsonstr);}
4.1如果到时有传对象:
public ResultJSON getUserList() {// 假设我们从数据库查询到了一些用户数据List<User> users = new ArrayList<>();users.add(new User("john_doe", "john.doe@example.com"));users.add(new User("jane_doe", "jane.doe@example.com"));// 使用 ResultJSON 封装结果return new ResultJSON(200, "查询成功", users);}