Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - JQuery $.ajax() post - data in a 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"); });

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

UPDATE: Code fixed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...