Javascript JQuery $.ajax() 在 Java servlet 中发布数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10214723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:20:27  来源:igfitidea点击:

JQuery $.ajax() post - data in a java servlet

javascriptjqueryajaxhashmap

提问by iJared

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:

我想将数据发送到 java servlet 进行处理。数据将具有可变长度并以键/值对形式存在:

{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }

The data doesn't need to be formated this way, it is just how I have it now.

数据不需要以这种方式格式化,这正是我现在拥有的方式。

var saveData = $.ajax({
      type: "POST",
      url: "someaction.do?action=saveData",
      data: myDataVar.toString(),
      dataType: "text",
      success: function(resultData){
          alert("Save Complete");
      }
});
saveData.error(function() { alert("Something went wrong"); });

The $.ajax()function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...

$.ajax()功能运行良好,因为我确实收到了“保存完成”的警报。我的困境是在 servlet 上。如何检索数据?我尝试使用这样的 HashMap ......

HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());

...but hmturns out to be null which I am guessing means the .getParameterMap()isn't finding the key/value pairs. Where am I going wrong or what am I missing?

...但hm结果是 null 我猜这意味着.getParameterMap()没有找到键/值对。我哪里出错了或者我错过了什么?

回答by aquinas

You don't want a string, you really want a JS map of key value pairs. E.g., change:

你不想要一个字符串,你真的想要一个键值对的 JS 映射。例如,改变:

 data: myDataVar.toString(),

with:

和:

var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }



var saveData = $.ajax({
      type: 'POST',
      url: "someaction.do?action=saveData",
      data: myKeyVals,
      dataType: "text",
      success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

jQuery 理解这样的键值对,它不理解大字符串。它只是将它作为字符串传递。

UPDATE:Code fixed.

更新:代码已修复。

回答by Harish Verma

Simple method to sending data using java script and ajex call.

使用java脚本和ajax调用发送数据的简单方法。

First right your form like this

首先像这样正确你的表格

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

sumbit 后表单 id #frm_details 上的 javascript 逻辑目标

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

回答by iJared

For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

目前,我走的路线与我之前所说的不同。我将格式化数据的方式更改为:

  &A2168=1&A1837=5&A8472=1&A1987=2

On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

在服务器端,我使用 getParameterNames() 将所有键放入 Enumerator,然后遍历 Enumerator 并将键和值放入 HashMap。它看起来像这样:

Enumeration keys = request.getParameterNames(); 
HashMap map = new HashMap(); 
String key = null; 
while(keys.hasMoreElements()){ 
      key = keys.nextElement().toString(); 
      map.put(key, request.getParameter(key)); 
}

回答by atjua

To get the value from the servlet from POSTcommand, you can follow the approach as explained on this postby using request.getParameter(key)format which will return the value you want.

要获得从servlet中值POST命令,你可以采取的办法是在解释这个职位通过request.getParameter(key)将返回所需的值格式。