2013-06-05 30 views
1

我是使用Java開發Web應用程序的新手。我正在嘗試建立一個AJAX調用。這是我創建的一些任意代碼。Servlet + jQuery/Ajax - 未知的令牌o

的Servlet

 Map<String, String> testJson = new HashMap<String, String>(); 
    String Key = "someKey"; 
    String Value = "someValue"; 

    testJson.put(Key, Value); 

    response.setContentType("application/json"); 
    response.setCharacterEncoding("UTF-8"); 
    response.getWriter().write(new Gson().toJson(testJson)); 
} 

jQuery的

$(document).on("click","#register-user", function(){ 
    $.ajax({ 
     type: 'GET', 
     url: 'Register', 
     success: function(data){ 
      alert($.parseJSON(data)); 
     } 
    }); 
    return false; 
}); 

回調函數的工作沒有任何的Json所以AJAX是好的。但是當我嘗試發回一個用Json編碼的Java對象時,我得到一個「Uncaught exception。Unexpected token o」。我究竟做錯了什麼?

+0

你能提供'data'的內容? – emesx

回答

1

試試這個

Gson gson = new GsonBuilder().create(); 
String json = gson.toJson(testJson); 

或試試這link

有點像這樣

Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType(); 
String json = gson.toJson(map, typeOfMap); 

以上的更多的例子,然後返回絃樂器JSON

+0

似乎無法在gson包內找到TestTypes類。 – user1683645