1. 程式人生 > >ajax不執行success回撥而是執行error回撥

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");
								}
						}						

					});
				}
			});
		}