Pass json data to servlet (doPost) with Jquery $.ajax

你离开我真会死。 提交于 2019-12-08 15:44:44

I did this changes for solve my problem:

1) In ajax call change method: POST by type: 'POST'.

2) Add even.preventDefault() before call to ajax for dont use submit by default.

3) Change the form i handled data request. If i dont pass a form i need do this for retrieve request parameter like @Sabya explain.

4) Handle json inside of success (ajax) for show selection of html select.

So the code is the next:

JavaScript

<script type="text/javascript">
var j = jQuery.noConflict();
var abcd = document.getElementById("abcd");
var selection = abcd.options[abcd.selectedIndex].value
j(document).ready(function(){
   j.ajax({
          url: '/bin/company/repo',
          dataType:'JSON',
          success:function(data){
             jQuery.each(data, function(text, value){
             j('#abcd').append('<option id="' + value.value + '">' + value.text + '</option>');
        });
      },
      error:function(){
        //if there is an error append a 'none available' option
        j('#abcd').html('<option id="-1">none available</option>');
      }
   });
   j("#abcd").live('change',function(){
      var combo = document.getElementById('abcd');
      if(combo.selectedIndex<0)
        alert('no option selected');
      else 
        selection = combo.options[combo.selectedIndex].value;
   });

   j('form').on('submit', function(e){
      event.preventDefault();
      j.ajax({type: 'POST',
         contentType: "application/json; charset=utf-8",
         url: "/bin/company/repo",
         dataType: 'JSON',
         data: JSON.stringify({ "text": selection }), 
         success:function(data){
            jQuery.each(data, function(text, value){
                 j('#demo').html('');
                 j('#demo').html(value.text);
            });
         }}); 
   });
})
</script>

Servlet

@Override
protected void doPost(SlingHttpServletRequest request,       SlingHttpServletResponse response) throws ServletException,
        IOException {
        response.setHeader("Content-Type", "application/json");
        PrintWriter out = response.getWriter();
        StringWriter writer = new StringWriter();
        TidyJSONWriter json = new TidyJSONWriter(writer); 
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        String data = buffer.toString();
        try 
        {   
           JSONObject jsonObj = new JSONObject(new String(data));
           json.array();
           //loop through your options and create objects as shown below 
           json.object();
           json.key("text");
           json.value(jsonObj.get("text"));
           json.endObject();
           //end your array 
           json.endArray();
        } catch(JSONException e) {
            e.printStackTrace();
        }
        out.write(writer.toString());

}

Use .live() in place of .change() because you select element is dynamic.

j("#abcd").live('change', function(){
    var combo = document.getElementById('abcd');
    if(combo.selectedIndex<0)
        alert('No hay opcion seleccionada');
    else 
        abcdVal = combo.options[combo.selectedIndex].value;
        alert('La opcion seleccionada es: '+combo.options[combo.selectedIndex].value);
});

Can you inspect the servlet call in network panel of chrome and check the Request-Header and/or form data ?

Not sure about your problem in javascript , but if you are getting an NPE in your servlet , that might be because you are not POSTing it as a form data and trying to retrieve it from request parameter.

Accessing the data sent as a Request Payload is a little different than accessing the form data.

The following snippet might help you in case you find that you are POSTing the JSON to the servlet as a Request Payload.

        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        String requestData = buffer.toString();

        //TODO: Retrieve required fields from this requestData string .
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!