2014-01-30 64 views
0

我有一個視圖窗體,其中包含一個帶有文本框的表格。 我需要將表格的信息保存在數據庫中。作爲parameterJSONArray傳遞給Spring控制器

* javascript函數*

function sendTableToServer() 
{ 
    var table; 
    table = document.getElementById('myTable'); 
    var rowLength = table.rows.length; 
    var tableArray = [rowLength -1]; 

    var JSONObject; 

    for (var tblRow = 1; tblRow < rowLength; tblRow++){ 
      console.log("***** ROW CHANGE *****"); 

      JSONObject = { 
       "rowIndex": "myTableRow" + tblRow, 
       "partNo": table.rows[tblRow].cells[0].firstChild.value, 
       "partName":table.rows[tblRow].cells[1].firstChild.value,      
      }; 
     f24Array[tblRow] = JSONObject; 
    } 
    console.log(f24Array[rowLength-1]["rowIndex"]); 
    console.log(f24Array.length -1); 

     $.getJSON("f24BatcCreateEAF.do", { 
      type: "F24", 
      pRefForm: "DVL", 
      pF24Values: tableArray 
      } 
     , function(ans) { 
      console.log("The row is" +ans.strVar); 
     } 
    ); 
}; 

*控制器*

public @ResponseBody 
AjaxReturnMessage createEaf(Model model, HttpServletRequest pRequest, @RequestParam String type, @RequestBody String[] pF24Values) throws Exception { 

    long eafId=0; 
    AjaxReturnMessage pARM = new AjaxReturnMessage(); 
    log.info("entering creatEaf); 

     try { 

      System.out.println("calling gF24BatchService"); 

      eafId = gF24BatchService.createEAFRow(model, pp, type, pRefForm, pDescription); 


      pARM.setId(eafId); 
      pARM.setStrVar("f24TableRow1"); 
      pARM.setCode(AjaxReturnMessage.STATUS_ERROR); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // return the jsp page only 
     return pARM; 

} 

當我觸發sendTableToServer功能我得到一個錯誤 「404」。 但是,如果我從JSON調用中刪除pF24Values,並且他的服務沒有錯誤。

如何在不需要創建新的對象類型的情況下「捕捉」pF24Values?這可能嗎?

感謝

回答

0

您正在執行GET到控制器,使控制器只能捕獲通過請求參數數據。另外,你的getJSON函數也發送所有的數據作爲請求參數。

因此,您的控制器必須將pF24Values作爲@RequestParam而不是@RequestBody捕獲。

如果你想發送複雜的數據結構到你的控制器上,你需要做一個POST,把JSON作爲請求體(比如說) - 雖然你可以使用GET來獲取數組數據,但不是你在這裏做的方式 - 每行需要有一個單獨的請求參數(例如pF24Values:onepF24Values:two等 - 有幾種方法可以做到這一點)。

+0

感謝您的幫助mckdos 因此,使用表單並使用@RequestBody將信息捕獲爲POST會解決問題嗎? 你能給我一個簡單的例子,我已經看到很多使用類型爲「employee」或「anmal」的對象作爲例子的示例,但如果可能的話,它喜歡粘貼一個字符串數組。 – Yan

+0

我在我的手機上,因此我無法檢查代碼是否對不起,並且不會再在PC附近待一天。但jist是用JSON編碼你的表格數據,然後將數據發佈到請求主體中。你的控制器應該不需要太多的改變,除非解組JSON(Spring可以自動完成這個操作?)。 – nickdos

+0

您是否嘗試過使用POST呢?這個帖子可能會有所幫助http://stackoverflow.com/questions/5908466/jquery-spring-mvc-requestbody-and-json-making-it-work-together – nickdos

相關問題