0
servlet有問題。我通過XMLHttpRequest將表單數據發送到服務器,但servlet錯誤地處理了請求對象併發送響應對象「null.null」。我嘗試了以下的東西,但沒有什麼幫助:XMLHttpRequest請求/ Servlet響應爲空
- encodeupported「document.getElementsByName('contractor')。value」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);
}
}
}
的Java:
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);
}
}
'httpRequest.open('POST',「/ AjaxServ」,true);'不包含上下文路徑。 –
你是什麼意思? – aime
我的意思是如果你在'http:// localhost/project/testpage'上測試你的項目,並且你的文章在'/ AjaxServ'上,它會在'http:// localhost/AjaxServ'上發佈,所以你會得到404錯誤,你可以用Firebug(網絡)或任何工具來嘗試查看HTTP請求 –