2014-12-06 64 views
1

我使用一個動作文件創建了一個Java Web應用程序,該文件從數據庫生成數據到JSON數組。現在,我想把這個JSON數組傳遞給jQuery?這怎麼可能?如何將JSON數組從Struts 2動作類傳遞給jQuery?

僅供參考。我應用了Struts 2,Spring和Hibernate框架。我沒有使用這個應用程序的PHP。

更新:

這是我的Struts 2的操作方法:

public static String jsonData = null; 

public String generateJson() throws Exception 
{ 
    JSONObject json = null; 
    JSONArray jsonArray = new JSONArray(); 

    this.records = this.recordManager.getAllRecords(); 

    for (RecordEntity record : records) 
    { 
     json = new JSONObject(); 

     json.put("id", record.getId()); 
     json.put("firstname", record.getFirstName()); 
     json.put("lastname", record.getLastName()); 
     json.put("due", record.getDue()); 
     json.put("email", record.getEmail()); 
     json.put("website", record.getWebsite()); 
     jsonArray.put(json); 
    } 

    System.out.println(jsonArray.toString()); 

    jsonData = jsonArray.toString(); // jsonData will be passed to jQuery 
    return SUCCESS; 
} 

這是我的jQuery。我使用BootstrapTable所以這樣的結構,我想jsonData的值傳遞給這個jQuery:

$('#record').bootstrapTable({ 
    method : 'get', 
    data: jQuery.parseJSON(VALUE_OF_jsonData_HERE), 
    cache : ... 
    ... 
    ... 
}); 
+1

如果servlet在響應輸出中打印JSON編碼的數據,則您只需通過常規的ajax請求獲取它即可['$ .getJSON'](http://api.jquery.com/jQuery.getJSON/) – 2014-12-06 15:29:34

+0

如何?抱歉,我沒有提及,我是servlets和Struts 2的新手。 – Dylan 2014-12-06 15:31:56

+0

也可以直接在頁面中將json輸出到javascript變量中。方法在某種程度上取決於它的使用方式 – charlietfl 2014-12-06 15:32:40

回答

0

使用阿賈克斯會幫助你,

this上手,也請先閱讀關於Ajax的第一個背景

+0

是的,我已經使用過。請注意我修改了問題並添加了代碼。 :) – Dylan 2014-12-06 15:46:16

相關問題