2012-12-13 4 views
0

json 객체 배열을 서블릿에서 javascript로 보내려고합니다. 모든 배열을 가져 와서 구문 분석합니다. 내 아약스하지만 자바 스크립트 끝 에서 JSON 배열을받을 수 없습니다 도와주세요 적절하게 서블릿을 호출Json을 서블릿에서 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(); 
    }  

}

이 내가 JSON 개체의 배열을 얻기 위해 노력하고 있어요 자바 스크립트 내 아약스 호출입니다 서블릿을 형성하십시오.

$.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

이렇게 서블릿에 요청하고 json으로 응답하는 방법입니다. 내가 자바 GSON 라이브러리 Google을 사용하고 당신도 조언을 사용하는 것이 좋습니다.

$.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 
       } 
       } 

https://code.google.com/p/google-gson/ 서블릿 나는 이것이 분명 희망

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 
} 

입니다. 그렇지 않다면, 의견에 저에게 물어보십시오.

관련 문제