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

Javascript 使用Jquery$.ajax将json数据传递给servlet(doPost),javascript,jquery,ajax,servlets,aem,Javascript,Jquery,Ajax,Servlets,Aem,我正在学习对ajax的调用,因此我试图获得html选择的'abcd'值。我在用这句话: abcdVal=combo.options[combo.selectedIndex].value 当此值更改时,我必须将其值存储在类似abcdVal的变量中,以便通过以下方式传递到servlet: var data={text:abcdVal} 我得到了该值,并以纯文本的形式进行响应,但在html页面中我看到: [{文本:null,值:10}] 而不是[{text:html select的selected值,

我正在学习对ajax的调用,因此我试图获得html选择的'abcd'值。我在用这句话:

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

当此值更改时,我必须将其值存储在类似abcdVal的变量中,以便通过以下方式传递到servlet:

var data={text:abcdVal}

我得到了该值,并以纯文本的形式进行响应,但在html页面中我看到:

[{文本:null,值:10}]

而不是[{text:html select的selected值,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>

使用.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作为请求负载发布到servlet,下面的代码段可能会对您有所帮助


我这样做是为了解决我的问题:

ajax调用更改方法中的1:POST by type:'POST'

2在调用ajax之前添加even.preventDefault,以便默认情况下不使用submit

3更改我处理数据请求的表单。如果我没有传递表单,我需要为retrieve请求参数执行此操作,如@Sabya explain

4在success ajax中处理json以显示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>

是的,谢谢。你知道如何解决这个问题吗?我想现在我必须使用一个BufferedReader或其他东西来读取servlet中的数据@当我请求时,Brijesh Bhatti得到null。getParametertext;-@Brijesh Bhatt您正在使用哪个jquery版本@jmhdezuse。居住在……上,如回答中所述。。并检查servlet中的文本参数..现在不应为null@jmhdezSame->null。我相信问题在于我何时发送数据或营救他。错误的sintax或错误的方式-@Brijesh Bhatt可能代码可以更干净,但这是一个解决方案-@Sabya
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);
});
        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        String requestData = buffer.toString();

        //TODO: Retrieve required fields from this requestData string .
<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>
@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());

}