2014-04-30 48 views
0

我試圖返回一個JSON對象從這個JSP page.But我不知道爲什麼它不提供所需results.Here返回是我的jsp頁面:JSON對象沒有被jsp頁面

<%@page import="net.sf.json.JSONException"%> 
<%@page import="net.sf.json.JSONArray"%> 
<%@page import="net.sf.json.JSONObject"%> 
<%@page contentType="application/json" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="application/json; charset=UTF-8"> 
    <title>JSP Page</title> 
</head> 
<body> 
    <% 

      JSONObject json  = new JSONObject(); 
      JSONArray employeeslist = new JSONArray(); 
      JSONObject employee; 
      try 
      { 
       int count = 15; 

       for (int i=0 ; i<count ; i++) 
       { 
        employee = new JSONObject(); 
        employee.put("name"  , "Decepticons" + i); 
        employee.put("id"  , "1999" + i); 

        employeeslist.add(employee); 
       } 
       json.put("Employeeslist", employeeslist); 
      } 
       catch (JSONException jse) 
       { 

       } 

      out.write(json.toString()); 
    %> 
</body> 
</html> 

請幫我找到這段代碼中的錯誤。

我的AJAX調用此JSP:

<script type="text/javascript"> 
$(document).ready(function() { 
    $("input[type=button]").click(function() { 
     $.ajax({ 
     url: 'ValidEmployeeList.jsp', 
     dataType: 'json', 
     success: function(data) { 
      //alert(data); 
      alert(JSON.stringify(data)); 
     }, 
     error: function() { 
      alert('error'); 
     } 
    }); 

    }); 
}); 
</script> 

回答

0

您將Json內容類型與html格式混合。嘗試的開始和結束刪除HTML標籤:

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="application/json; charset=UTF-8"> 
<title>JSP Page</title> 
</head> 
<body> 

而且

</body> 
</html> 

最後千萬不要使用空的catch塊。你可能會錯過一些重要的例外,這是真正的原因。

0

JSON的變量從未被超越分配創建新的,空的,JSONObject的。您只能使用員工和員工列表。但你永遠不會打印出來。

+0

我沒有得到你。 – user3522121

+0

如果你正在談論這個Ajax代碼,然後我編輯它。它給出錯誤警報。 – user3522121

+0

另外我確實使用json tostring()來打印出JSONObject – user3522121