jquery中ajax的基本使用
今天介紹的是普通的ajax使用方法
實現對用戶的校驗及其登錄
效果:
源代碼:
jsp頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.1.1.min.js"></script>
<style>
div{
width: 300px;
height: 300px;
margin: auto;
}
</style>
</head>
<body>
<div>
<form action="#">
賬號:<input type="text" name="name" id="name"/><br/>
密碼:<input type="text" name="pwd" id="pwd"/><br/>
<input type="button" value="登錄"/>
</form>
</div>
<script>
$(function () {
$("#name").blur(function () { // 鼠標失去焦點判斷
var rs1 = /^[\u4e00-\u9fa5]+$/;
var name = $(this).val();
if(rs1.test(name)){
$(this).css("border-color","blue"); //格式正確邊框設置爲藍色
}else{
$(this).css("border-color","red"); //格式錯誤邊框設置爲紅色
}
});
$("#pwd").blur(function () { // 鼠標失去焦點判斷
var rs2 = /^[0-9]+$/;
var pwd = $(this).val();
if(rs2.test(pwd)){
$(this).css("border-color","blue"); //格式正確邊框設置爲藍色
}else{
$(this).css("border-color","red"); //格式錯誤邊框設置爲紅色
}
});
$(":button").click(function () { // 當點擊提交提交按鈕後,發送AJAX請求
$.ajax({
url:"ajaxServlet", // 請求路徑
type:"post", // 請求方式
data:{ // 發送的請求參數
name:$("#name").val(),
pwd:$("#pwd").val()
},
dataType:"text", // 返回值的類型
success:function (data) { // 回調函數
alert(data);
}
});
});
});
</script>
</body>
</html>
Servlet頁面:
package com.hnpi.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ajaxServlet")
public class ajaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8"); // 轉換編碼
String name = "王五"; // 定義用於判斷登錄的用戶名
String pwd = "123"; // 定義用於判斷登錄的密碼
String ajaxName = request.getParameter("name"); // 接收AJAX發送的參數
String ajaxPwd = request.getParameter("pwd");
if(name.equals(ajaxName) && pwd.equals(ajaxPwd)){ // 判斷用戶名和密碼是否正確
response.getWriter().write(ajaxName + "歡迎您!"); // 返回給用戶的信息
}else{
response.getWriter().write("用戶名或密碼錯誤!");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}