XMLHttpRequest请求/ Servlet响应为空

时间:2014-02-27 16:45:18

标签: ajax servlets

servlet存在问题。我通过XMLHttpRequest将表单数据发送到服务器,但是servlet错误地处理请求对象并发送响应对象“null.null”。我尝试了一些事情,但没有任何帮助:

  • 编码“document.getElementsByName('contractor')。value”by encodeURIComponent;
  • 将FormData的对象作为参数传递给.send();
  • 将表单中的enctype属性更改为“multipart / formdata”;
  • 使用get方法。

请看一下。如果有任何建议如何在不使用jQuery的情况下使其工作,我会非常感激。

HTML:

<div id="request-form">
    <form enctype="application/x-www-form-urlencoded" method="post">
        Contractor<input type="text" name="contractor"><br>
        Contract No<input type="text" name="contract-no">
        <input type="button" onclick=clickOnButton() value="Submit"><br>
    </form>
</div>

JS:

var httpRequest;

function clickOnButton() {
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var dataForRequest = 'contract=' + document.getElementsByName('contractor').value + '&contract-no=' + document.getElementsByName('contract-no').value;
    httpRequest.onreadystatechange = responseHandler;
    httpRequest.open('POST', "/AjaxServ", true);
    httpRequest.send(dataForRequest);
}

function responseHandler() {
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            var line = httpRequest.responseText;
            alert(line);
        }
    }
}

爪哇:

public class ServletClass extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String contractor = req.getParameter("contractor");
        String contractNo = req.getParameter("contract-no");
        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter();
        out.write(contractor + "." + contractNo);
    }
}

1 个答案:

答案 0 :(得分:1)

不应该是'contractor=' + document.getElementsByName('contractor').value而不是'contract=' + document.getElementsByName('contractor').value {{1}}?