背景:有個增刪改頁面,用jquery祭出ajax異步調用接口,spring mvc響應對象是個json字符串,jquery根據響應結果判斷,若是刪除成功給出提示。那麼問題來了,接口裏響應的字符串怎麼匹配頁面的字符串來判斷是否刪除成功?jquery
具體場景以下:ajax
jquery文件spring
getCacheDate: function(cacheName, key, operationType) { var _this = this; $.ajax({ url: _this.host + "getCacheData", dataType: "json", method: "post", data: { cacheName: cacheName, key: key, operationType: operationType }, success: function(result) { $(".loading").addClass("loading-hide"); if(result == "delete success"){ _this.jsonData = {}; $(".json-renderer").trigger("DeleteDataSuccess"); }else{ _this.jsonData = result; $(".json-renderer").trigger("GetDataSuccess"); } }, error: function(err) { console.log(err); $(".loading").addClass("loading-hide"); $(".json-renderer").trigger("GetDataFailed"); } }); },
spring controller類json
@RequestMapping(value = "/getCacheDate", method = RequestMethod.POST, produces = "application/json;charset=utf-8") public @ResponseBody String getCacheDate(MemcacheBeanRequest memcacheBeanRequest) { // 獲取緩存操做信息 String operationType = memcacheBeanRequest.getOperationType(); String cacheName = memcacheBeanRequest.getCacheName(); String key = memcacheBeanRequest.getKey(); if (StringUtils.isEmpty(operationType) || StringUtils.isEmpty(cacheName) || StringUtils.isEmpty(key)) { return null; } // 執行緩存操做,獲得結果 return memcacheViewService.doMemcached(operationType, cacheName, key); }
看到這裏很明顯了,個人getCacheData接口必須返回delete success這個字符串,去匹配jquery裏的result字符串對象,才能提示刪除成功。問題轉化爲Controller接口getCacheData返回什麼。若是想固然的覺得就返回字符串"delete success",那麼很抱歉,這是不對的,由於Controller註解@ResponseBody要求咱們返回的是一個json字符串,而不僅僅是一個純字符串。假如getCacheData真的返回"delete success",那麼頁面會進入error分支,而不是success分支,由於頁面沒法解析該result文本:緩存
[object Object]
memcacheview.js (208,11)
{
[functions]: ,
__proto__: { },
readyState: 4,
responseText: "delete success",
status: 200,
statusText: "parsererror"
}
到這裏問題又轉化爲響應出去的json是什麼。咱們知道json是鍵值對格式的,因此不能單純這樣響應"{\"delete success\"}",這種格式同樣是頁面沒法解析的。咱們知道value確定就是"delete success",那麼key我這裏選用msg,getCacheData接口返回"{\"msg\":\"delete sucess\"}",jquery判斷條件改成if(result.msg == "delete sucess"),問題解決。mvc