0

我正在尝试将 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 调用,我试图从 servlet 中获取 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);
      }

}); 
4

2 回答 2

1

这对我有用,下面是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');
    }
});

小服务程序:

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

有关更多详细信息,请参阅此处

于 2020-09-12T17:02:08.463 回答
0

这就是我向 servlet 发出请求并用 json 响应的方式。我使用 google GSON library for 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
                }
                }

这是小服务程序

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
}

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

于 2013-09-25T19:39:01.947 回答