jquery ajax请求成功,返回了数据,但是不进success的问题

来源:互联网 发布:曼德拉效应知乎 编辑:程序博客网 时间:2024/06/06 02:45

问题:jquery ajax请求成功,返回了数据,但是不进success的分支。(被这个问题困扰了2天)

问题代码描述:

controller类代码:

/** * 向页面输出json对象 * @param response * @param jsonStr */protected void repPrintJson(HttpServletResponse response,String jsonStr) {response.setCharacterEncoding("UTF-8");response.setContentType("application/json");PrintWriter out = null;try {out = response.getWriter();out.print(jsonStr);out.flush();} catch (IOException e) {logger.error(e);} finally {if (null != out) {out.close();}}}


jsp代码:

$.ajax({type : "POST",url : "###.do",data : {goodsName : goodsName,goodsProperty : goodsProperty,goodsId : goodsId,pageNo : pageNo},dataType: "text",success : function(data) {//TODOvar arr = data.list;},error: function(XMLHttpRequest, textStatus, errorThrown) {//TODO}});

需要返回json字符串:

String retJsonStr = "{\"limitEnd\":15,\"limitStart\":0,\"list\":[{\"catalogId\":23,\"costPrice\":123,\"description\":\"<p>\\r\\n    去玩儿去玩儿车</p>\\r\\n\",\"distributorId\":\"PD1000003\",\"externalCatalogId\":100,\"externalCatalogName\":\"日用\",\"goodsId\":43,\"goodsName\":\"测试用1\",\"goodsProperty\":\"001001\",\"goodsPropertyCn\":\"实物\",\"marketPrice\":\"122\",\"parentCatalogId\":1,\"parentCatalogName\":\"家居百货1\",\"payType\":\"01\",\"providerId\":\"P1000045\",\"purePointsPrice\":12,\"salePrice\":43,\"saleRefPrice\":\"\",\"shortenedForm\":\"测1\",\"stableCashPrice\":23,\"stablePointsPrice\":34,\"status\":\"03\",\"stock\":\"9999\"}],\"msg\":\"success!\",\"statusKey\":\"00\",\"totalCount\":1}";


此json字符串中包含特殊字符换行,controller类中直接转换json格式的时候,出现异常,导致页面ajax一直进入error分支,不会进入success分支。抛出异常parseerror。

这是由于java HttpServletResponse 将含有特殊字符的json字符串转换成json对象时不识别导致。可以返回页面String类型。



解决方案:

controller代码:

<pre name="code" class="java">/** * 向页面输出json字符串 * @param response * @param jsonStr */protected void repPrintJson(HttpServletResponse response,String jsonStr) {response.setCharacterEncoding("UTF-8");response.setContentType("<span style="color: rgb(73, 73, 73); font-family: simsun; font-size: 14px; line-height: 21px; background-color: rgb(252, 211, 221);">text/plain;</span>");PrintWriter out = null;try {out = response.getWriter();out.print(jsonStr);out.flush();} catch (IOException e) {logger.error(e);} finally {if (null != out) {out.close();}}}


jsp代码:
$.ajax({type : "POST",url : "###.do",data : {goodsName : goodsName,goodsProperty : goodsProperty,goodsId : goodsId,pageNo : pageNo},dataType: "text",success : function(data) {//TODO<pre name="code" class="java">                        var data = eval("("+dataTxt+")");
},error: function(XMLHttpRequest, textStatus, errorThrown) {//TODO}});

问题已经解决。



参考文章:

1)http://my.oschina.net/adwangxiao/blog/78509

2)http://wkf41068.iteye.com/blog/1767342

1 0
原创粉丝点击