JQuery $ .ajax()post - java servlet中的数据 [英] JQuery $.ajax() post - data in a java servlet

查看:116
本文介绍了JQuery $ .ajax()post - java servlet中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送数据到一个java servlet进行处理。数据将有一个可变长度,并在键/值对:

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

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

$。ajax()罚款,因为我得到一个保存完成的提醒。我的困境在servlet上。我如何检索数据?我尝试使用这样的HashMap ...

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

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

...但 hm 为空,我猜测意味着 .getParameterMap()没有找到键/值对。

...but hm turns 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?

推荐答案

你不想要一个字符串,你真的想要一个JS地图的关键值对。例如,更改:

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

 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理解这样的键值对,它不理解大字符串。它将其简单地作为字符串传递。

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

更新:修正了代码。

这篇关于JQuery $ .ajax()post - java servlet中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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