将Json从servlet发送到javascript

时间:2012-12-13 19:44:07

标签: ajax json java-ee

我正在尝试将一个json对象数组从servlet发送到javascript。我都得到了数组并解析。 我的ajax适当调用servlet但无法在javascript端接收json数组 请帮忙

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);
      }

}); 

2 个答案:

答案 0 :(得分: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
}

我希望这很清楚。如果没有,请在评论中问我。

答案 1 :(得分:0)

这对我有用,下面是ajax代码。

$.ajax({
    type : 'POST',
    url : "URL",
    data: {array: array},
    success : function(response)
    {
        alert("Success "+response.message);
    },
    error : function(response)
    {
        alert("Error"+response.message);
        console.log('Error');
    }
});

Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    String[] array = request.getParameterValues("array[]");
    request.setCharacterEncoding("utf8");
    response.setContentType("application/json");
    ArrayList<String> message = new ArrayList<String>();
    message.add("response message goes here");
    PrintWriter writer = response.getWriter();
    JSONObject obj = new JSONObject();
    obj.put("message",message); 
    response.setStatus(200);
    //System.out.println(obj.get("message"));
    writer.append(obj.toString());
    writer.close();
}

有关更多详细信息,请参见here