2015-07-10 147 views
0

基本上我有我創建一個JSON對象的HTML文件:如何將JSON對象轉換爲servlet?

function CreateJson() { 
     var tableObj = []; 

     var loopCounter = 0; 
     var inputValues = []; 

     var table = document.getElementById('inputTable'); 
     for (var r = 0, n = table.rows.length; r < n; r++) { 
      for (var c = 0, m = table.rows[r].cells.length; c < m; c++) { 
       loopCounter++; 

       inputValues.push(table.rows[r].cells[c].firstChild.value); 

       if (loopCounter == 3) { 
        tableObj.push({ 
         model : inputValues[0], 
         colour : inputValues[1], 
         year : inputValues[2] 
        }); 
        loopCounter = 0; 
        inputValues = []; 
       } 
      } 
     } 
     $.ajax({ 
      type : 'POST', 
      dataType : 'json', 
      data: { tableObj : JSON.stringify(jsondata)}, 
      url : 'ServletUrl', 
      timeout : 5000, 
      success : function(data, textStatus) { 
       // whatever 
      }, 
      error : function(xhr, textStatus, errorThrown) { 
       // whatever 
      } 
     }); 
    } 

我有一個action我的Java servlet形式,當我提交表單,JavaScript代碼上面得到執行。如何檢索和解析我的servlet中的JSON對象? JSON對象是tableObj

編輯: 我編輯CreateJson功能:

,在我的servlet我有:

public void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws IOException { 

     Object json = request.getParameter("tableObj"); 
     System.out.println(json); 

在它打印空的日誌。

+0

我不理解你的 題。 TableObj是一個json對象?你想在servlet中獲得它嗎?你發送它? –

+0

如何發送tableObj到servlet。我想在我的servlet中使用tableObj –

+0

您是否嘗試將它發佈到servlet,例如使用jquery? http://api.jquery.com/jquery.post/ –

回答

0

查看正在使用POST在您的Java腳本

$.ajax({ 
      type : 'POST', 
      dataType : 'json', 
      data: { tableObj : JSON.stringify(jsondata)}, 
      url : 'ServletUrl', 
      timeout : 5000, 
      success : function(data, textStatus) { 
       // whatever 
      }, 
      error : function(xhr, textStatus, errorThrown) { 
       // whatever 
      } 
     }); 

,但使用的是不相同的動詞(的doPost)在servlet,請更改

public void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws IOException { 

public void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws IOException { 
+0

您無法在Servlet實現中將doGet()更改爲doPost()。你必須聲明兩種方法。 –

+0

我想說的是,嗨讀的是doGet中的值,而不是他必須在doPost中讀取它,而且你是正確的兩種方法都屬於同一個接口... –

+0

我將其更改爲鍵入:'GET ',但我的doGet函數仍然返回null。 –