后端传到前端的字符串,只要前端以json接收,用console.log()显示时候就是标准的json格式,但是使用循环遍历就是字符串的格式。看一下案例代码:
后端代码如下
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
response.setContentType("text/html;charset=utf-8");
Object result=JsonString.getJsonString();
String json = JSON.toJSONString(result);
response.getWriter().print(json);
}
public class JsonString {
public static String getJsonString() throws IOException {
String JsonStringValues=null;
File file=new File(JsonString.class.getResource("/data.json").getFile());
return JsonStringValues=FileUtils.readFileToString(file, JsonStringValues);
}
}
一看成功使用fastjson成功完成转化,
接着就是前端的接收数据(使用的是mui框架,其它也是类似的可以有参考意义的)
mui.ajax("GetDataServlet", {
dataType : "json", //服务器返回json格式数据
type : "get", //HTTP请求类型
timeout : 10000, //超时时间设置为10秒;
headers : {
"Content-Type" : "application/json"
},
success : function(data) {
console.log(data);
//服务器返回响应,根据响应结果,分析是否登录成功;
var html = template("test", data);
document.getElementById("list").innerHTML = html;
},
error : function(xhr, type, errorThrown) {
//异常处理;
//console.log(type);
}
});
<script id="test" type="text/html">
{{each stories as value i}}
<li style="width:100%;height: 75px;background-color: #FFFFFF;padding: 10px;margin-bottom: 10px;overflow: hidden;">
<span style="float: left;width: calc(100% - 72px);">
{{value.title}}
</span>
<span style="float: right;margin-left: 10px;">
<img width="62px" height="55px" src="{{value.images[0]}}"/>
</span>
</li>
{{/each}}
</script>
显示都一堆字符串格式的东西,
这时就使用console.log(data);打印出来接收到的东西,确实json格式,
放在标签里面显示字符串。这是就出现前后端的互不承认问题所在。最后采取使用一般写死的json在前端处理,没有问题,排除了前端的框架错误,才好好的看后端代码。
在后端加上System.out.println("println.json=" + json);
打印在控制台确实是字符串,原来转混乱了。最后Servlet中的get方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置
// 设置不缓存图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
response.setContentType("text/html;charset=utf-8");
/*response.setContentType("text/text;charset=utf-8");*/
// 指定生成的相应图片
Object result=JsonString.getJsonString();
//String json = JSON.toJSONString(result);
System.out.println("println.json=" +result);
response.getWriter().print(result);
}
实现了前端的
这时再来看看前端的console.log(data);
显示
后端的显示也是jsong格式
这才是正确的传输方式;
总结:
(1)后端json是否传对看后台控制台是否为json格式
(2)前端检查是否接收的是正确格式的object对象,前端以json格式接收实际是接收的json的object对象。
备注:
后端加入了一个jar包
commons-io-1.4.jar
前端: