2012-12-13 37 views
0

我想發送一個json對象數組從一個servlet到javascript。我所有的數組和解析。 我的AJAX調用servlet適當,但未能收到在JavaScript的結束 JSON數組,請幫助發送JSON從servlet到javascript

public void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws IOException { 
    System.out.println("Post!!"); 
    response.setContentType("application/json");//since sendign jsonArray toString 
    PrintWriter out = response.getWriter(); 
    try { 
     Marker marker=new Marker(40.72318,-74.03605);// 

     JSONArray arrayObj=new JSONArray(); 
     arrayObj.add(marker); 
     System.out.println(marker.toString()); 
     out.print(arrayObj); 

    } finally { 
     out.flush(); 
     out.close(); 
    }  

}

這是在JavaScript我Ajax調用,我想獲得的JSON對象數組組成servlet。

$.ajax({ 
      url:'test', 
      dataType:'json', 
      type:'POST', 
      success:function(data){ 

      <%System.out.println(" success");%> 
      console.log(data); 
      alert('got json hopefully'); 
      alert(data); 
      // 
     }, 
     error:function(jxhr){ 
      <%System.out.println(" faliure");%> 
     console.log(jxhr.responseText); 
     } 

}); 
+0

你作爲迴應得到什麼? – SDReyes

回答

0

這是我向servlet發出請求並用json迴應的方式。我使用谷歌GSON庫的Java和我建議你也使用它。 https://code.google.com/p/google-gson/

$.ajax({ 
       url: 'servletName', //the mapping of your servlet 
       type: 'POST', 
       dataType: 'json', 
       data: $('#someForm').serialize(), 
       success: function(data) { 
         if(data.isValid){ 
        //maybe draw some html 
       }else{ 
        //data is not valid so give the user some kind of alert text 
       } 
       } 

這是servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    String someInput = request.getParameter("someInput"); 

    Map map=new HashMap(); 


     if(someInput!=null){ //or whatever conditions you need 
       map.put("isValid",true); 
       map.put("someInput",someInput); 
     }else{ 
     map.put("isValid", false); 

     } 
     write(response,map); 
    } 



private void write(HttpServletResponse response, Map<String, Object> map) throws IOException { 
    response.setContentType("application/json"); 
    response.setCharacterEncoding("UTF-8"); 
    response.getWriter().write(new Gson().toJson(map)); //this is how simple GSON works 
} 

我希望這是顯而易見的。如果沒有,請在評論中問我。