2016-10-10 124 views
0

我從在servlet的Ajax調用如何從jsp接收和解析json數據?

$.ajax({ 
    cache : false, 
    type : "GET", 
    url : "UserServlet?id=" + userId, 
    success : function(result) { 
     alert(result.profileUser); 
    } 
}); 

發送一個JSON像

User profileUser = userService.get(id); 
request.setAttribute("profileUser", profileUser); 
JSONObject json = new JSONObject(); 
try { 
    json.put("profileUser", profileUser); 
} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
response.setContentType("application/json"); 
response.getWriter().write(json.toString()); 

而在JavaScript警告的結果是給我Entity.user但如果我想打電話給result.profileUser。該用戶的uuid或屬性未定義返回給我。誰能幫幫我嗎?

+0

什麼是實際的HTTP響應? – SLaks

+0

@SLaks 302臨時移動 – joesid

回答

1

如果你發送的JSON到Ajax客戶機,那麼你需要指定你即將收到JSON類型。像這樣:

$.ajax({ 
    cache : false, 
    type : "GET", 
    dataType : "json", 
    url : "UserServlet?id=" + userId, 
    success : function(result) { 
     alert(result.profileUser); 
    } 
}); 

這將導致您的成功方法評估結果參數爲json對象。

0

更改阿賈克斯以下幾點:

$.ajax({ 
    cache : false, 
    type : "GET", 
    url : "UserServlet?id=" + userId, 
    success : function(profileUser) { 
     alert(profileUser.uuid); 
    } 
});