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

问题: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) {			
			//TODO
			var arr = data.list;
		},		
		error: function(XMLHttpRequest, textStatus, errorThrown) {			
			//TODO
		}
	});


需要返回json字符串:

String retJsonStr = "{\"limitEnd\":15,\"limitStart\":0,\"list\":[{\"catalogId\":23,\"costPrice\":123,\"description\":\"

\\r\\n 去玩儿去玩儿车

\\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代码:

/**
	 * 向页面输出json字符串
	 * @param response
	 * @param jsonStr
	 */
	protected void repPrintJson(HttpServletResponse response,
			String jsonStr) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain");
		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		
            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、打开支付宝首页搜索“8282987” 立即领红包。

2、扫码领红包。

标题。

你可能感兴趣的:(java语言)