我正在发布一个jQuery AJAX POST到一个servlet并且数据是JSON字符串的形式。 它成功发布,但在Servlet端,我需要将这些key-val对读入会话对象并存储它们。我尝试使用JSONObject类,但我无法得到它。在servlet中读取JSON字符串
继承人的代码片断
$(function(){
$.ajax(
{
data: mydata, //mydata={"name":"abc","age":"21"}
method:POST,
url: ../MyServlet,
success: function(response){alert(response);
}
});
Servlet的侧
public doPost(HTTPServletRequest req, HTTPServletResponse res)
{
HTTPSession session = new Session(false);
JSONObject jObj = new JSONObject();
JSONObject newObj = jObj.getJSONObject(request.getParameter("mydata"));
Enumeration eNames = newObj.keys(); //gets all the keys
while(eNames.hasNextElement())
{
// Here I need to retrieve the values of the JSON string
// and add it to the session
}
}
为什么不创建一个JavaScript对象mydata,其中包含mydata.name,mydata.age?那么你可以只是拉你的servlet的具体参数,而不是解码json? – dmcnelis 2011-03-17 12:30:23
我不能'因为key-val可以从POST到另一个不同 – sv1 2011-03-17 12:37:52
你可以在你的函数中使用JQuery解码json时,fwiw。不是说应该是你的解决方案,但它会完成同样的事情。 – dmcnelis 2011-03-17 12:46:51