原生ajax非同步請求和跨域請求例項
阿新 • • 發佈:2019-01-05
客戶端:
實現註冊的功能,對使用者名稱進行驗證
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>註冊介面</title> <script type="text/javascript"> //驗證使用者名稱是否重複 function checkName(obj) { //1.根據瀏覽器建立非同步引擎物件 xhr = createXMLHttpRequest(); //2.設定非同步引擎物件的屬性 //2.1設定回撥方法 xhr.onreadystatechange = callback; //2.2設定請求路徑和請求方式 xhr.open("POST", "http://localhost:8080/RegisterAjax03/system/checkName.do", true); //2.3設定請求的標頭檔案資訊 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //3.呼叫非同步引擎物件的send方法請求,並傳遞請求的引數 //3.1資料打包 var data = "username=" + obj.value; //3.2傳送請求 xhr.send(data); } function createXMLHttpRequest() { //ie8以上的瀏覽器建立非同步引擎物件 if (window.XMLHttpRequest) { return new XMLHttpRequest(); } } function callback() { if (xhr.readyState == 4 && xhr.status == 200) { var data = xhr.responseText.replace(/\r\n/g,''); if ("success" == data) { document.getElementById("message").innerHTML = "該使用者名稱可以使用"; flag = true; } else if ("fail" == data){ document.getElementById("message").innerHTML = "對不起,該使用者名稱已經被佔用"; flag = false; } } } function isLogin() { if (flag == true) { //1.根據瀏覽器建立非同步引擎物件 xhr = createXMLHttpRequest(); //2.設定非同步引擎物件的屬性 //2.1設定回撥方法 xhr.onreadystatechange = callbacklogin; //2.2設定請求路徑和請求方式 xhr.open("POST", "system/register.do", true); //2.3設定請求的標頭檔案資訊 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //3.呼叫非同步引擎物件的send方法請求,並傳遞請求的引數 //3.1資料打包 var username = document.getElementById("username").value; var password = document.getElementById("password").value; var data = "username=" + username + "&password=" + password; //3.2傳送請求 xhr.send(data); }else{ alert("請重新設定使用者名稱"); } } function callbacklogin() { if (xhr.readyState == 4 && xhr.status == 200) { var data = xhr.responseText; alert("註冊成功"); } } </script> </head> <body> <table border="0"> <tr> <td>使用者名稱:</td> <td><input type="text" id="username" onblur="checkName(this)" /></td> <td><span id="message"></span></td> </tr> <tr> <td>密碼:</td> <td><input type="password" id="password" /></td> <td></td> </tr> <tr> <td colspan="2" align="center"><input type="button" onclick="isLogin()" value="註冊" /></td> </tr> </table> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登入介面</title> <script type="text/javascript"> function isLogin() { xhr = createXMLHttpRequest(); xhr.onreadystatechange = callBack; xhr.open("POST", "http://127.0.0.1:8080/LoginAjax03/system/login.do", true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); var username = document.getElementById("username").value; var password = document.getElementById("password").value; var data = "username=" + username + "&password=" + password; xhr.send(data); } function createXMLHttpRequest() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } } function callBack() { if (xhr.readyState == 4 && xhr.status == 200) { var data = xhr.responseText.replace(/\r\n/g,''); if (data == "no") { alert("登入失敗,請仔細核對使用者名稱和密碼"); } else if (data == "yes") { alert("登入成功") } } } </script> </head> <body> <table border="0"> <tr> <td>使用者名稱:</td> <td><input type="text" id="username" /></td> </tr> <tr> <td>密碼:</td> <td><input type="password" id="password" /></td> <td></td> </tr> <tr> <td colspan="2" align="center"><input type="button" onclick="isLogin()" value="登入" /></td> </tr> <tr> <td colspan="2" align="right"><a href="register.jsp">使用者註冊入口</a> </td> </tr> </table> </body> </html>
package com.system.controller; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.util.DBUtil; public class CheckNameController extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); // 資料庫查詢 Connection conn = null; PreparedStatement pre = null; ResultSet rs = null; String data = ""; try { conn = DBUtil.getConn(); String sql = "select username from t_login where username=?"; pre = conn.prepareStatement(sql); pre.setString(1, username); rs = pre.executeQuery(); if (rs.next()) { data = "fail"; } else { data = "success"; } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(rs, pre, conn); request.setAttribute("data1", data); request.getRequestDispatcher("/checknamedata.jsp").forward(request, response); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
服務端:
跨域實現使用者的登入<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
${data }
package com.system.controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.util.DBUtil;
public class LoginController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement pre = null;
ResultSet rs = null;
String data = "";
try {
conn = DBUtil.getConn();
String sql = "select * from t_login where username = ? and password = ?";
pre = conn.prepareStatement(sql);
pre.setString(1, username);
pre.setString(2, password);
rs = pre.executeQuery();
if (rs.next()) {
data = "yes";
}else{
data = "no";
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
request.setAttribute("data", data);
request.getRequestDispatcher("/data.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
}
注意的幾個點:
1.ajax從後臺返回的值預設帶一行空白行,需要對資料進行處理
var data = xhr.responseText.replace(/\r\n/g,'');
2.跨域請求的關鍵程式碼 response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET");
3.在寫程式碼中發現不同程式的返回值要用不同的data.jsp去處理,否則沒有效果