2012-10-26 59 views
1

的Spring MVC控制器返回響應我有一個簡單JQuery函數調用我Spring MVC控制器:無法顯示使用JSON和JQuery

function createDatabaseRecord() { 
    if (isFormValid()) { 
     $.getJSON(
       "${pageContext.servletContext.contextPath}${databaseConfigUrl}", 
       {name:$('#idName').val(), 
        databaseName:$('#idDatabaseName').val(), 
        hostName:$('#idHostName').val(), 
        username:$('#idUsername').val(), 
        password:$('#idPassword').val()}, 
       function (data) { 
        var html = '<span>' + data + '</span>'; 
        $('#idMessage').html(html); 
       } 
     ); 
    } 
} 

當我點擊按鈕的功能調用,一切都很好。問題是此行:$('#idMessage').html(html);不能按預期方式工作。我在同一個JSP頁面內有一個<div>元素。這是由函數調用

<div id="idMessage"> 
</div> 

我的春天控制器的方法:

@RequestMapping(value = DATABASE_CONFIG_RECORD_MAPPING, method = RequestMethod.GET) 
public 
@ResponseBody 
String createDatabaseConfiguration(@RequestParam(value = "name", required = true) String name, 
            @RequestParam(value = "databaseName", required = true) String databaseName, 
            @RequestParam(value = "hostName", required = true) String hostName, 
            @RequestParam(value = "username", required = true) String username, 
            @RequestParam(value = "password", required = true) String password) { 
    try { 
     DatabaseConfig config = new DatabaseConfig(); 
     config.setName(name); 
     config.setDatabaseName(databaseName); 
     config.setHostName(hostName); 
     config.setUsername(username); 
     config.setPassword(password); 
     configService.save(config); 
    } catch (Exception ex) { 
     LOGGER.error("Exception while create database configuration record.", ex); 
     return "Error occurred while creating database configuration record: " + ex.getMessage(); 
    } 
    return "Database configuration record successfully created."; 
} 

我可以在螢火看到反應過來對我說:

enter image description here。這是消息:已成功創建數據庫配置記錄。我期望能在<div>元素中顯示,但不會顯示。有人知道哪裏可能是問題嗎?如果您需要更多代碼,請詢問。

+0

如果CONSOLE.LOG(數據);在設置html之前,它返回什麼? –

回答

1

您的回覆不是JSON格式。

試試這個片段在你的控制器:

return Collections.singletonMap("result", "Database configuration record successfully created"); 

而且使用它在JavaScript這樣的:

var html = '<span>' + data.result + '</span>'; 
+0

謝謝,完美的工作:) –

1

我絕對不是Java的專家(雖然看起來不錯),但認爲你的問題來自於你使用jQuery的getJSON方法,但你的視圖只是返回純文本。

您需要將您的響應轉換爲JSON,或使用$.get$.ajax改爲更加手動的AJAX請求。

+0

如果我把'getJSON'改成'ajax',我得到:'NetworkError:400 Bad Request'。這不起作用。 –

+0

我的歉意。我原本只有'$ .ajax',但需要更多的選項來控制它。我使用'$ .get'作爲替代方法。 [jQuery AJAX文檔](http://api.jquery.com/category/ajax)具有您需要選擇應調用哪種方法的所有信息。 – Joshua