【发布时间】:2011-07-17 08:56:57
【问题描述】:
我将 jQuery AJAX POST 发布到 servlet,数据采用 JSON 字符串的形式。 它已成功发布,但在 Servlet 方面,我需要将这些键值对读入会话对象并存储它们。我尝试使用 JSONObject 类,但我无法得到它。
这里的代码是sn-p
$(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
}
}
【问题讨论】:
-
为什么不创建一个包含 mydata.name、mydata.age 的 javascript 对象 mydata?那么你可以只在你的servlet中提取特定参数而不是解码json?
-
我不能因为键值可以从一个 POST 到另一个不同
-
你可以在你的函数中使用 JQuery 解码 json 时,fwiw。不是说应该是你的解决方案,但它会完成同样的事情。