【问题标题】:Pass json data to servlet (doPost) with Jquery $.ajax使用 Jquery $.ajax 将 json 数据传递给 servlet (doPost)
【发布时间】:2015-04-06 10:21:32
【问题描述】:

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

abcdVal = combo.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 select的选定值),"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.  
}

【问题讨论】:

    标签: javascript jquery ajax servlets aem


    【解决方案1】:

    我做了这些改变来解决我的问题:

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

    2) 在调用 ajax 之前添加 even.preventDefault() 以默认不使用提交。

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

    4) 在成功 (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>
    

    小服务程序

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

    【讨论】:

    • 可能代码可以更干净,但这是一个解决方案 - @Sabya
    【解决方案2】:

    使用 .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);
    });
    

    【讨论】:

    • 我做到了,谢谢。你知道如何解决这个问题吗?我现在在想,我必须使用 BufferedReader 或其他东西来读取 servlet 中的数据。 - @Brijesh Bhatt
    • 我在做 request.getParameter("text"); 时得到了 null - @Brijesh Bhatt
    • 您使用的是哪个 jquery 版本? @jmhdez
    • 使用 .live 代替 on .. 如答案 .. 中所写并检查 servlet 中的文本参数 .. 它现在不应为空 .. @jmhdez
    • 相同 -> 空。我相信问题出在我发送数据或营救他的时候。错误的语法或错误的方式 - @Brijesh Bhatt
    【解决方案3】:

    你能在 chrome 的网络面板中检查 servlet 调用并检查 Request-Header 和/或表单数据吗?

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

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

    如果您发现将 JSON 作为 Request Payload 发布到 servlet,以下 sn-p 可能会对您有所帮助。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多