-
我想问下大家,你们平时一般后台给前端传递数据的时候,同一类的数据,要以不同格式展示
1.是由后端处理好了传给前台(前端要一种数据格式,后台就得去相应写一套)
2.还是说后台只传给前台一套数据格式,至于怎么去用,由前端自己去解析
例如下面的例子,第一种格式是在列表展现的时候用的,第二种格式是在统计报表的时候用的
列表数据格式
[
{
"id": 1,
"name": "zhangsan",
"money": 1000
},
{
"id": 2,
"name": "lisi",
"money": 2000
},
{
"id": 3,
"name": "wangwu",
"money": 3000
}
]
统计图数据格式
{
"names": [
"zhangsan",
"lisi",
"wangwu"
],
"money": [
1000,
2000,
3000
]
}
先提供一点非常优秀的 restful 资源,这些资料有详细讲到
url/error codes/response
的设计,包括错误码与http status code
的对应,都有比较详细的资料。REST API Tutorial
REST API Best Practices PDF
RESTful 接口返回值
response
应该设计为统一格式,就像楼主上面的设计其实是有很大问题的,在实际场景中使用会很复杂,因为你只考虑到了正确
场景,如果是错误
场景应该怎么办?这个时候是不是同一个接口会返回多种不同的数据格式接口使用方使用时就会非常不便。code – contains the HTTP response status code as an integer.
status – contains the text: “success”, “fail”, or “error”. Where “fail” is for HTTP status response values from 500-599, “error” is for statuses 400-499, and “success” is for everything else (e.g. 1XX, 2XX and 3XX responses).
message – only used for “fail” and “error” statuses to contain the error message. For internationalization (i18n) purposes, this could contain a message number or code, either alone or contained within delimiters.
data – that contains the response body. In the case of “error” or “fail” statuses, this contains the cause, or exception name.
大概的设计就是有
code/status/message/data
4个规范属性。返回结果示例:
成功:
失败: