Ajax簡單來說就是通過js來向后端發(fā)送請求,相比使用表單通過跳轉來實現(xiàn)發(fā)送請求,Ajax可以做到頁面不刷新并獲取后端響應。
HTML代碼:
并沒有使用表單發(fā)送
<body>
<form id="interface">
<p>注冊</p>
<div id="input1">
<p>用戶名</p><input type="text" name="user_name" id="user_name"/>
<div id="state_box">
<div id="user_name_state">
<div class="state_icon" id="user_name_state_icon"></div>
<p></p>
</div>
</div>
</div>
<div id="input2">
<p>密碼</p><input type="text" name="user_password" id="user_password"/>
<div id="user_password_state">
<div class="state_icon" id="user_password_state_icon"></div>
<p></p>
</div>
</div>
<input type="button" value="注冊" id="enroll"/>
</form>
</body>
JS代碼:
簡單使用了JSON
window.onload=function(){
var xhr = new XMLHttpRequest();
document.getElementById("enroll").addEventListener("click",function(){
uns.removeAttribute('class');
xhr.open("POST","/Ajax/check",true);
xhr.setRequestHeader("Content-Type","application/json");
var json = JSON.stringify({
"user_name":document.getElementById("user_name").value.toString(),
"user_password":document.getElementById("user_password").value.toString()
})
xhr.send(json);
})
var uns = document.getElementById("user_name_state");
var unsi = document.getElementById("user_name_state_icon");
xhr.addEventListener("readystatechange",function(){
if(xhr.readyState==4&&xhr.status==200){
uns.style.opacity=1;
uns.setAttribute('class',"shake");
switch(xhr.responseText.toString()){
case "user_name too long":
unsi.style.cssText="background: url(error.png) no-repeat;background-size: contain;background-position: center;";
unsi.nextSibling.nextSibling.innerText="用戶名過長";break;
case "user_name is empty":
unsi.style.cssText="background: url(error.png) no-repeat;background-size: contain;background-position: center;";
unsi.nextSibling.nextSibling.innerText="你要做甚?";break;
case "user_name is available":
unsi.style.cssText="background: url(correct.png) no-repeat;background-size: contain;background-position: center;";
uns.lastChild.previousSibling.innerText="";break;
case "user_name has been occupied":
unsi.style.cssText="background: url(error.png) no-repeat;background-size: contain;background-position: center;";
unsi.nextSibling.nextSibling.innerText="用戶名已被占用";break;
}
}
})
}
JAVA代碼:
調用JDBC
@WebServlet("/LhdServlet")
public class LhdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LhdServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
System.out.println("收到請求");
System.out.println(request.getContentType());
request.setCharacterEncoding("utf-8");
//讀取JSON數(shù)據(jù)
BufferedReader br = new BufferedReader(request.getReader());
StringBuffer json = new StringBuffer();
String line = null;
while((line=br.readLine())!=null) {
json.append(line);
}
String info = json.toString();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(info);
String name = object.get("user_name").getAsString();
String password = object.get("user_password").getAsString();
System.out.println("name:"+name+'\n'+"password:"+password);
//獲取用戶名稱長度(單位為字節(jié)),UTF-8下一個漢字占3個字節(jié)
int user_name_length = object.get("user_name").getAsString().length();
if(user_name_length>21) {
response.getWriter().write("user_name too long");
}
else {
if(user_name_length == 0) {
response.getWriter().write("user_name is empty");
}
else{
System.out.println("開始核對用戶名");
//注冊MySQL數(shù)據(jù)庫服務器的驅動
try {
DriverManager.registerDriver(new Driver());
//獲取與MySQL數(shù)據(jù)庫服務器的連接
//jdbc:主協(xié)議
//mysql:子協(xié)議
//127.0.0.1:數(shù)據(jù)庫服務器是位于哪臺PC上,可以用ip/域名表示
//3306 數(shù)據(jù)庫默認端口
//users:表示MySQL數(shù)據(jù)庫服務器上具體的數(shù)據(jù)庫
String url = "jdbc:mysql://127.0.0.1:3306/users";
Connection conn = (Connection) DriverManager.getConnection(url, "root", "lhd123");
System.out.println(conn!=null?"連接成功":"連接失敗");
//創(chuàng)建封裝SQL語句的對象
Statement stmt = (Statement) conn.createStatement();
//處理結果集
String sql = "select username from information where username='"+name+"'";//ctrl+shift+x快速大寫
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
conn.close();
System.out.println("用戶名重復");
response.getWriter().write("user_name has been occupied");
}
else {
conn.close();
System.out.println("用戶名可用");
response.getWriter().write("user_name is available");
}
}
catch(SQLException e){
e.printStackTrace();
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
效果:

