JavaWeb 返回json数据的两种方式
1.说明
由于一般情况下,由浏览器(前端)发送请求,服务器(后台)响应json数据,所以这里结合js进行说明;
A服务器发送请求至B服务器,并接收其返回的json数据,见文末推荐,这里不再赘述!
2.服务器返回json数据
方式一:返回JSON格式数据(JSON对象)
// 设置返回json数据并指定字符集 response.setContentType( "application/json;charset=utf-8;" ); // 设置返回数据 JSONObject jo = new JSONObject(); jo.put( "name" , "Marydon" ); // 返回数据 response.getWriter().print(jo);
方式二:返回JSON格式字符串(JSON字符串)
// 设置返回字符集
response.setContentType( "charset=utf-8" );
String result = "{\"name\":\"Marydon\"}" ;
// 返回数据
response.getWriter().print(result);
3.客户端接收并处理json数据
对于第一种返回格式
$.get();$.ajax();$.post();$.getJSON()这4种方式不用再做多余的处理,直接就能取值。
$.post(baseUrl + "/test.do" , function (result){
alert(result.name); // Marydon
});
对于第二种返回格式
$.get();$.ajax();$.post();这三种方式需要对数据进行处理,才能取值;
$.get(baseUrl + "/test.do" , function (result){
// json字符串-->json对象
result = eval( '(' + result + ')' );
alert(result.name); // Marydon
});
$.getJSON();这种方式直接就能取值,无需再做处理。
$.getJSON(baseUrl + "/test.do" , function (result){
alert(result.name); // Marydon
});
写在最后
哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!
相关推荐:
本文来自博客园,作者:Marydon,转载请注明原文链接:https://www.cnblogs.com/Marydon20170307/p/9367559.html
浙公网安备 33010602011771号