ajax不执行success回调而是执行error回调

  

       调试代码遇到一个问题,就是前台执行删除操作后,controller返回数据,但前台接收时,ajax不执行success回调,总是弹出失败的对话框.接收数据类型是json.


先看看我的前台代码.

if (rows) {
			$.messager.confirm('警告', '确定删除吗?', function(r) {
				if (r) {
					$.ajax({
						type : 'post',
						url : 'deleteStudentTeachClass',
						data : {
							"ids" : ids
						},
						dataType : 'json',  
						traditional : true,  
						success : function(result) { 							
							$.messager.alert("提示", "恭喜您,删除成功", "info");
							$("#dg").datagrid("reload");
						},
						error : function(msg) {
							$.messager.alert("提示", "操作失败", "info");
							$("#dg").datagrid("reload");
						}

					});
				}
			});
		}


下面是后台controller代码

@RequestMapping(value = "/deleteStudentTeachClass")
			public void deleteStudentTeachClass(String ids, HttpServletRequest request,
					HttpServletResponse response) throws Exception {
						
				String dataBaseName = "itoo_platform";
				String[] strArray = null;
				strArray = ids.split(",");
				Boolean flag = false;
				String result = "false";
				try {
					flag = schoolTeachingBean.deleteStudentTeachClass(strArray,
							dataBaseName);
					if (flag == true) {
						result = "success";
					}
				} catch (RuntimeException e) {
					e.printStackTrace();
				}
				outToJson.outJson(response, result);
			}


         通过查询发现dataType如下的说明: 


         "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.) 

        也就是说jquery1.4版本以后对json格 式要求非常严格,要满足json.org网站定义的格式才能执行success回调,否则都会出错,无法解析返回的json数据.我看了下返回到前台的字符串,的确不是严格的json格式.


于是把后台返回值改成了这样:

if (flag == true) {
	result = "{\"result\":true}";
}


但无论返回true还是false都执行success回调,这让我更郁闷.百思不得其解.

最终把前台判断改成了这样:


if (rows) {
			$.messager.confirm('警告', '确定删除吗?', function(r) {
				if (r) {
					$.ajax({
						type : 'post',
						url : 'deleteStudentTeachClass',
						data : {
							"ids" : ids
						},
						dataType : 'text',  
						traditional : true,  
						success : function(result) {							
							if(result=='true'){
								$.messager.alert("提示", "恭喜您,删除成功", "info");
								$("#dg").datagrid("reload");
								}
							else{
								$.messager.alert("提示", "操作失败", "info");
								$("#dg").datagrid("reload");
								}
						}						

					});
				}
			});
		}




  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值