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

淺唱寂寞╮ 提交于 2019-12-23 04:05:42

问题


i'm learning about calls to ajax so i'm trying to get the value of ('#abcd') (a html select). I'm using this line:

abcdVal = combo.options[combo.selectedIndex].value

When this value change i must store his value in a var like abcdVal for pass to servlet with:

var data = {"text" : abcdVal};

j("#mybutton").click(function(){    
    j.ajax({method: 'POST',
        url: "/bin/company/repo",
        dataType: 'JSON',
        data: data, 
        success:function(result){
            alert(result);
            j("#demo").html('');
            j('#demo').html(result);
        }});
});

i got the value and put in response as a text plain, but in html page i see:

[{"text":null,"value":10}]

Instead of [{"text":(selected value of html select),"value":10}]

i doing something wrong then i pass the data to servlet. how must i pass this var correctly?


My code

Javascript code

<script type="text/javascript">
var j = jQuery.noConflict();
var abcdVal;
j(document).ready(function(){
   //get a reference to the select element
  //request the JSON data and parse into the select element
  j.ajax({
      url: '/bin/company/repo',
      dataType:'JSON',
      success:function(data){
        //clear the current content of the select
        j('#abcd').html('');
        //iterate over the data and append a select option
        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").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);
});
var data = {"text" : abcdVal};
alert(data);
j("#mybutton").click(function(){    
    j.ajax({method: 'POST',
        url: "/bin/company/repo",
        dataType: 'JSON',
        data: data, 
        success:function(result){
            alert(result);
            j("#demo").html('');
            j('#demo').html(result);
        }});
});
})
</script>

Servlet code

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,
        IOException {
        String text = (String) request.getParameter("text");
        response.setHeader("Content-Type", "text/html; charset=UTF-8");
        StringWriter writer = new StringWriter();
        TidyJSONWriter json = new TidyJSONWriter(writer); 
        try 
        {   
           json.array();
           //loop through your options and create objects as shown below 
           json.object();
           json.key("text");
           json.value(text);
           json.key("value");
           json.value(10);
           json.endObject();
           //end your array 
           json.endArray();     
        } catch(JSONException e) {
            e.printStackTrace();
        }

       response.getWriter().write(writer.toString());      // Write response body.  
}

回答1:


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

}



回答2:


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



回答3:


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 .


来源:https://stackoverflow.com/questions/29469366/pass-json-data-to-servlet-dopost-with-jquery-ajax

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