AJAX請求參數數組解決辦法

最近涉及到需要用AJAX(基於JQUERY)發送請求傳遞數組參數,如下:假設j是個數組

$.ajax({
       type : "POST",
       url : '../../../system/downloadFile',
       traditional: true,//取消深度序列化
       data: {
        name:j
       },
       dataType: "json",
success : function(data) {
           if(data.isSuccess == "true" || data.isSuccess == true) {
           } else{
           }
}
   });

Controller裏打斷點name爲NULL值,如下:

@RequestMapping({ "downloadFile" })
public @ResponseBody Object downloadFile(HttpServletRequest request,@RequestParam(value = "name", required=false) String name) {

return null;// CommonUtils.convertBeanToJson(sibList);
}

上網查資料得知AJAX對數組參數有一個序列化的過程,導致後臺服務獲取,後來總結可以通過兩種方法實現:

1.JS中AJAX請求處加入raditional: true,告訴AJAX不要深度序列化,後臺返回一個類似於拼接後的字符串,並且需要split(當然還有別的方式),但是這種方法有個BUG,截取時候容易定位混淆。

2.將數組JSON化

function arrayToJson(o) {
    var r = [];
    if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof o == "object") {
      if (!o.sort) {
        for (var i in o)
          r.push(i + ":" + arrayToJson(o[i]));
        if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
          r.push("toString:" + o.toString.toString());
        }
        r = "{" + r.join() + "}";
      } else {
        for (var i = 0; i < o.length; i++) {
          r.push(arrayToJson(o[i]));
        }
        r = "[" + r.join() + "]";
      }
      return r;
    }
    return o.toString();
  }




後臺返回字符串,個人認爲這種方法比較靠譜。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章