JSON
JavaScript Object Notation,⼀种轻量级数据交互格式,完成 js 与 Java 等后端开发语⾔对象数据之间的转换。
客户端和服务器之间传递对象数据,需要用JSON格式。
package com.southwind.entity; public class User { private Integer id; private String name; private Double score; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getScore() { return score; } public void setScore(Double score) { this.score = score; } public User(Integer id, String name, Double score) { this.id = id; this.name = name; this.score = score; } } User user = new User(1,"张三",96.5);
var user = { id:1, name:"张三", score:96.5 }
package com.southwind.servlet; import com.southwind.entity.User; import net.sf.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/test") public class TestServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user = new User(1,"张三",96.5); //将 Java 对象转为 JSON 格式 resp.setCharacterEncoding("UTF-8"); JSONObject jsonObject = JSONObject.fromObject(user); resp.getWriter().write(jsonObject.toString()); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(function(){ var btn = $("#btn"); btn.click(function(){ $.ajax({ url:'/test', type:'post', dataType:'json', success:function(data){ $("#id").val(data.id); $("#name").val(data.name); $("#score").val(data.score); } }); }); }) </script> </head> <body> 编号:<input id="id" type="text"/><br/> 姓名:<input id="name" type="text"/><br/> 成绩:<input id="score" type="text"/><br/> <input id="btn" type="button" value="提交"/> </body> </html>
在开发微信小程序的时候,基本上使用的都是JSON语言
所以看了看JSON的格式以及基本用法