有更优雅的方法可以做到这一点,但这是最基本的。您需要将您的 javascript 变量组合成一个标准的帖子正文。
var postData = 'field1=' + value1;
postData += '&field2=' + value2;
postData += '&field3=' + value3;
/* You're concatenating the field names with equals signs
* and the corresponding values, with each key-value pair separated by an ampersand.
*/
如果您使用的是原始 XMLHttpRequest 工具,则此变量将是该send
方法的参数。如果使用 jQuery,这将是您的data
元素。
在您的 servlet 中,您从容器提供的 HttpServletRequest 对象中获取值。
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MyObject pojo = new MyObject();
pojo.setField1(request.getParameter("field1"));
pojo.setField2(request.getParameter("field2"));
pojo.setField3(request.getParameter("field3"));
/* Now your object contains the data from the ajax post.
* This assumes that all the fields of your Java class are Strings.
* If they aren't, you'll need to convert what you pass to the setter.
*/
}