ajax异步提交js
<script type="text/javascript">
var request;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
//用以拿到输入框的帐号和密码以及后台Servlet地址
function toLogin(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var url = "servlet/adminLoginServlet?username="+username+"&password="+password;
createRequest();
request.open("post",url,true);
request.onreadystatechange = processResponse;
request.send(null);
}
function MyLogin(){
document.getElementById("login").style.visibility="visible";
}
function processResponse(){
var res=request.responseText;
if (request.readyState == 4) { // 判断对象状态
if (request.status == 200) { // 信息已经成功返回,开始处理信息
//由后台Servlet传过来的信息
if(res=="登陆成功"){
//进入登录成功后的页面
window.location.href="../admin/welcome.jsp";
}else{
//在原登录页面显示登录失败的信息
window.alert(res);
}
} else { //页面不正常
window.alert("您所请求的页面有异常。");
}
}
}
</script>
<body>
<h2 aling="center">Ajax 异步请求</h2><hr>
账号:<input type="text" name="username" ><br>
密码:<input type="password" name="password" ><br>
<input name="submit" type="submit" class="buttom"
value="登 录" onClick="toLogin();return false;"/>
<input name="exit" type="reset" class="buttom"
value="重 置" />
</body>
java
<pre name="code" class="java">import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/xml; charset=utf-8");
PrintWriter out = response.getWriter();
if(username==null||password==null){
out.print("账号和密码不能为空!");
return;
}
if(username.equals("ajax")&&password.equals("java")){
out.print("登陆成功!");
return;
} else {
out.print("账号或密码错误!");
return;
}
}
}