使用Jquery $ .ajax将json数据传递到servlet(doPost) [英] Pass json data to servlet (doPost) with Jquery $.ajax

查看:94
本文介绍了使用Jquery $ .ajax将json数据传递到servlet(doPost)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习有关对Ajax的调用的信息,因此我试图获得('#abcd')(一个HTML选择)的值。我正在使用此行:

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

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

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

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


var data = { text:abcdVal};

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页面中,我看到了: / p>

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


[{ text:null, value:10}]

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

代替[{ text :( HTML select的选定值), value:10}]

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

我在做什么错误,然后我将数据传递给servlet。我该如何正确传递此变量?

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

我的代码

JavaScript代码

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

@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.  
}


推荐答案

我做了此更改以解决我的问题:

I did this changes for solve my problem:


1)在ajax调用更改方法中:POST类型: POST。

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

2)默认情况下,在调用ajax之前添加even.preventDefault()禁止使用。

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

3 )更改我处理数据请求的形式。如果我不通过表单,则需要执行此操作以获取诸如@Sabya说明之类的检索请求参数。

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)处理成功(ajax)内部的json以进行html select显示选择。

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

因此代码如下:

JavaScript

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

}

这篇关于使用Jquery $ .ajax将json数据传递到servlet(doPost)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆