直接说JSON
,感觉语义不太明确,最好还是说成JSON对象
或JSON字符串
。
假设前端通过ajax
回调函数接收数据,参数名为data
:
1 2 3 4 5 6 7
| $.post( "/xxx/yyy.do", $("#zzz-form").serialize(), function (data) { } );
|
JSON对象
当Content-Type
被设置为application/json
时:
1 2 3 4 5
| resp.setContentType("application/json; charset=UTF-8"); try (PrintWriter out = resp.getWriter()) { out.print("{\"status\": " + result.getStatus() + ", \"reason\": \"" + result.getReason() + "\"}"); out.flush(); }
|
前端收到的就是JSON对象
,可以直接获取里面的属性:
1 2 3
| function (data) { var reason = data.reason; }
|
JSON字符串
当Content-Type
不是application/json
时,比如是text/plain
:
1 2 3 4 5
| resp.setContentType("text/plain; charset=UTF-8"); try (PrintWriter out = resp.getWriter()) { out.print("{\"status\": " + result.getStatus() + ", \"reason\": \"" + result.getReason() + "\"}"); out.flush(); }
|
前端收到的就是JSON字符串
,此时需要将其解析为JSON对象
:
1 2 3 4
| function (data) { var json = JSON.parse(data); var reason = json.reason; }
|