所以我有一个基于Ajax的分配,该分配通过JavaScript将对象发送到Java Servlet。我的问题是-如何处理多个对象?
目标是将数据从JS发送(验证数据)到Java(计算结果),然后再发送到JS(从插入器打印)。
function validate() {
var num1 = document.getElementById("firstIn");
var data = "firstIn="+ encodeURIComponent(num1.value);
// var num2 = document.getElementById("secondIn"); //want to send this one as well
if (typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Main";
req.open("POST", url, true);
req.onreadystatechange = inserter();
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data); //Want to send multiple objects
}
==============================================================================
function inserter(){
if (req.readyState == 4) {
if (req.status == 200) {
var msg = req.responseText;
document.getElementById("msg").innerHTML = "<div>"+msg+"</div>";
}}}
@WebServlet("/add")
public class Main extends HttpServlet {
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setHeader("Cache-Control", "no-cache");
if (isNumeric(req.getParameter("firstIn")) && isNumeric(req.getParameter("secondIn"))) {
int one = Integer.valueOf(req.getParameter("firstIn"));
int two = Integer.valueOf(req.getParameter("secondIn"));
int sum = one + two;
String result = Integer.toString(sum);
resp.getWriter().write("result is " + sum);
} else {
resp.getWriter().write("Wrong values");
}
}
}
尝试过的方式:
//Splitting into two datas:
var data1 = "firstIn="+ encodeURIComponent(num1.value);
var data2 = "secondIn="+ encodeURIComponent(num2.value);
send({data1, data2};
//Putting objects in one data:
var data = "firstIn="+ encodeURIComponent(num1.value) + ", " +"secondIn="+
encodeURIComponent(num2.value);
send(data);