有更優雅的方式來做到這一點,但這是最基本的。你會想要將你的javascript變量組合到一個標準的post主體中。
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.
*/
}
來源
2013-11-09 23:18:24
Tap
謝謝您的答覆,我該怎麼添加到數據類型字段以取決於響應你從servlet發送類型的請求 – user1801279
。默認情況下,它是text/html,因此如果您發送的是xml,json,純文本等,則只需指定dataType。 – Tap