后台获取不到前台AJAX数据
<script>
window.onload = function (){
document.getElementById("btn").onclick = function (){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (){
if (xhr.readyState == 4) {
if (this.status == 200){
document.getElementById("mydiv").innerHTML = this.responseText
} else {
alert(this.status)
}
}
}
xhr.open("POST","/ajax/ajaxrequest4",true)
//模拟form表单提交数据
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//放到send()中的数据会自动在请求体当中提交数据
//使用JS代码获取用户名和密码
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
xhr.send("username"+username+"&password"+password)
}
}
</script>
@WebServlet("/ajaxrequest4")
public class AjaxRequest4Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//out.print("<font color='red'>hello ajax 4</font>");
//获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
out.print("用户名是:"+username+".密码是:"+password);
}
}