ajax不執行success回調而是執行error回調,ajaxsuccess
調試代碼遇到一個問題,就是前台執行刪除操作後,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");}}});}});}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。