本文首发于Daniate的个人网站,文章链接:https://daniate.com/archives/99/
直接说JSON
,感觉语义不太明确,最好还是说成JSON对象
或JSON字符串
。
假设前端通过ajax
回调函数接收数据,参数名为data
:
$.post(
"/xxx/yyy.do",
$("#zzz-form").serialize(),
function (data) {
// to do something
}
);
JSON对象
当Content-Type
被设置为application/json
时:
resp.setContentType("application/json; charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
out.print("{\"status\": " + result.getStatus() + ", \"reason\": \"" + result.getReason() + "\"}");
out.flush();
}
前端收到的就是JSON对象
,可以直接获取里面的属性:
function (data) {
var reason = data.reason;
}
JSON字符串
当Content-Type
不是application/json
时,比如是text/plain
:
resp.setContentType("text/plain; charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
out.print("{\"status\": " + result.getStatus() + ", \"reason\": \"" + result.getReason() + "\"}");
out.flush();
}
前端收到的就是JSON字符串
,此时需要将其解析为JSON对象
:
function (data) {
var json = JSON.parse(data);
var reason = json.reason;
}
本作品由Daniate采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。