使用Jquery$.ajax将json数据传递给servlet(doPost)

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

本文关键字:servlet doPost 数据 Jquery ajax json 使用      更新时间:2023-09-26

我正在学习对ajax的调用,所以我正在尝试获取('#abcd')(一个html选择)的值。我用的是这条线:

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

当这个值改变时,我必须将他的值存储在一个类似abcdVal的var中,以便传递给servlet:

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

我得到了值,并将其作为纯文本进行响应,但在html页面中我看到:

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

代替[{"text":(html选择的选定值),"value":10}]

我做错了什么,然后将数据传递给servlet。我必须如何正确地传递这个var?


我的代码

Javascript代码

<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代码

@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) 在ajax调用中,更改方法:按类型POST:"POST"。

2) 在调用ajax之前添加even.prventDefault(),默认情况下不使用submit。

3) 更改我处理数据请求的表单。如果我不传递表单,我需要这样做来检索请求参数,比如@Sabya explain。

4) 处理成功内部的json(ajax)以显示html选择的选择。

所以代码是下一个:

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

使用.live()代替.change(),因为您选择元素是动态的。

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

您能在chrome的网络面板中检查servlet调用并检查请求头和/或表单数据吗?

不确定您在javascript中的问题,但如果您在servlet中获得了一个NPE,那可能是因为您没有将其作为表单数据发布,并试图从请求参数中检索它。

访问作为请求有效负载发送的数据与访问表单数据略有不同。

如果您发现将JSON作为RequestPayload发布到servlet,以下片段可能会对您有所帮助。

        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        String requestData = buffer.toString();
        //TODO: Retrieve required fields from this requestData string .