//简单了解一下Ajax是什么?
//这是一个登录界面的jsp文件代码
<script type="text/javascript">
function login() {
//接收用户名
var uname = document.getElementById("uname").value;
var upwd = document.getElementById("upwd").value;
//声明一个xmlhttpRequest对象
var xmlhttp;
try{
xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
}
catch(e){
xmlhttp=new XMLHttpRequest();
}
//连接服务器
xmlhttp.open("post","LoginServlet?uname="+uname+"&upwd="+upwd,true);
//设置请求头信息
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//设置回调函数
xmlhttp.onreadystatechange=function(){
//判断请求响应结束
if(xmlhttp.readyState==4){
//服务器正常
if(xmlhttp.status==200){
//接收响应的数据
var str = xmlhttp.responseText;
if(str=="ok"){
document.getElementById("sp").innerHTML="✔";
}else{
document.getElementById("sp").innerHTML="×";
}
}
}
}
//发送
xmlhttp.send(null);
}
</script>
</head>
<body>
<form action="">
用户名:<input type="text" id="uname"><br>
密码:<input type="password" id="upwd" onblur="login()"><br>
<span id="sp"></span>
<input type="submit" value="登录">
<input type="reset" value="重置">
</form>
</body>
</html>
//其中所需要的包有:http://fastjson-1.1.jar ojdbc14.jar
//接下来是Servlet 来接收数据:
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收数据
String uname = req.getParameter("uname");
String upwd = req.getParameter("upwd");
System.out.println("uname:"+uname);
System.out.println("upwd:"+upwd);
resp.setCharacterEncoding("utf-8");
//获取响应的 输出流
PrintWriter out = resp.getWriter();
if("admin".equals(uname) && "123".equals(upwd)) {
out.print("ok");
}else {
out.print("no");
}
out.close();
}
}
//然后呢?了解一下Ajax的一些常用方法:
//补充一下:(就是在写的过程中可能会报错)以下图片是知道自己的错误信息的参考