问JSP中AJAX 做用户验证的简单问题
1. function check() {
var flag =false;
var xmlHttp;
function creatXMLHttp() {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXobject("Microsoft.XMLHTTP");
}
}
function checkuser(username) {
creatXMLHttp();
xmlHttp.open("POST", "../CheckUsername?username=" + username);
xmlHttp.onreadystatechange = checkuserCallback;
xmlHttp.send(null);
document.getElementById("msg").innerHTML="正在验证...";
}
function checkuserCallback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var text = xmlHttp.responseText;
if (text == "true")
document.getElementById("msg").innerHTML = "用户ID重复无法使用!";
flag=false;
} else{
document.getElementById("msg").innerHTML = "此ID可以使用";
flag=true;
}
}
}
function checkFrom(){
return flag;
}
</script>
2. 那请问我的CheckUsername(servlet)怎么写?
String username = request.getParameter("username");
Data_conn conn = new Data_conn();
System.out.println(conn);
String sql = "select count(username) from Login where username="
+ username + "";
ResultSet rs = conn.select(sql);
try {
if (rs.next()) {
out.print("true");
} else {
out.print("false");
}
请各位帮忙?
------解决方案--------------------讲Ajax的书上应该有的吧,不要太懒,看看书吧。
------解决方案--------------------package web;
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 ActionServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws
ServletException,
IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String uri = request.getRequestURI();
String action = uri.substring(uri.lastIndexOf("/"),
uri.lastIndexOf("."));
//检查用户名是否被占用。
if(action.equals("/check_name")){
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//模拟一个异常
if(1==2){
throw new ServletException("some error");
}
System.out.println("check_name...");
String username =
request.getParameter("username");
//查询数据库
if(username.equals("zs")){
out.println("用户名被占用");
}else{
out.println("可以使用");
}
}
out.close();
}
}
--------------------------------
if(username.equals("zs")){
out.println("用户名被占用");
}else{
out.println("可以使用");
}
的输出被 ajax中的 var text = xmlHttp.responseText; 拿到,原理是这样的
------解决方案--------------------String username = request.getParameter("username");
Data_conn conn = new