版权声明:转载请标明出处 https://blog.csdn.net/qq_41155191/article/details/82995147
<body>
<form action="" method="post">
用户名:<input type="text" id="uname" name="unme" />
密码:<input type="password" id="pwd" name="pwd"/>
<!--submit是整个表单自动提交 现在是要ajax提交-->
<input type="button" value="登录" id="btn"/>
</form>
<div id="result"></div>
<script>
var uname=document.getElementById("uname");
var pwd=document.getElementById("pwd");
var btn=document.getElementById("btn");
var result=document.getElementById("result");
btn.onclick=function () {
//发送ajax请求
var xhr;
//兼容浏览器
if (window.ActiveXObject){
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}else {
xhr=new XMLHttpRequest();
}
xhr.open("POST","http://192.168.15.222:8080/test/login.action",true);
//如果是post方式请求,那么就必须要模拟form表单
//get请求则不要
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//get请求,传参数
xhr.send("name="+uname.value+"&pwd="+pwd.value);
xhr.onreadystatechange=function () {
if ((xhr.readyState==4 || xhr.readyState=="complete") && xhr.status==200){
//得到相应值
result.innerHTML=xhr.responseText;
}
}
}
</script>
</body>