这是客户端代码:
function save(calc){
var request = new XMLHttpRequest();
request.open("POST","/Calculator/Controller?action=saveCalc",true);
//request.send("calc=calc") ---this does not work also
request.send(calc);
}
这是servlet:
if (action.equals("saveCalc")) {
String parameter = request.getParameter("calc");
System.out.println(parameter);
}
此处的参数为null ...
我也尝试过这样:
function save(calc){
var request = new XMLHttpRequest();
request.open("POST","/Calculator/Controller?action=saveCalc",true);
var data = new FormData();
data.append('calc', 'calc');
request.send(data);
}
也行不通。
如何获得此....参数。 :d
我取消了。这是解决方案: - 内容类型......
function save(calc){
var request = new XMLHttpRequest();
request.open("POST","/Calculator/Controller?action=saveCalc",true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("calc=" + calc);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("saveCalc")) {
String calc = request.getParameter("calc");
System.out.println(calc);
}
}
答案 0 :(得分:1)
首先你做错了,因为来自GET的参数通过URL传播,所以如果你使用POST并通过URL发送参数,这不应该在请求中传播,POST意味着参数由请求主体传播所以你必须做类似的事情:
var form = document.getElementById('subscribe_frm');
form.setAttribute("method", method);
form.setAttribute("action", path);
form.submit();
您可以先创建属性。
让代码在其中工作的另一种方法是:
request.open("GET","/Calculator/Controller?action=saveCalc",true);
将POST移至GET
答案 1 :(得分:0)
获取表单数据
var parameter = $("input#CountryVal").val();
dataString = "calc=" + parameter ;
进行Ajax调用
$.ajax({
type: "POST",
url: "/Calculator/Controller?action=saveCalc",
data: dataString,
dataType: "json",
//if received a response from the server
success: function( data, textStatus, jqXHR) {...}