欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Ajax從前端向后端發(fā)起請(qǐng)求的方法示例

 更新時(shí)間:2025年08月08日 10:25:03   作者:肖恩想要年薪百萬  
在前端使用AJAX向后端發(fā)送請(qǐng)求獲取數(shù)據(jù)是一項(xiàng)基本技能,下面這篇文章主要介紹了使用Ajax從前端向后端發(fā)起請(qǐng)求的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、重點(diǎn)思想

重點(diǎn)思想看過來哇!??!

  1. 我個(gè)人認(rèn)為做前后端分離的項(xiàng)目,無非就是前后端數(shù)據(jù)的相互傳遞,那么以這個(gè)思想為基礎(chǔ),學(xué)習(xí)收參和傳參的方式就顯得格外重要;
  2. 另外,我們是以JSON字符串的形式傳遞數(shù)據(jù)的,還需要學(xué)習(xí)JSON字符串的轉(zhuǎn)換與解析!

1、從前端向后端傳遞數(shù)據(jù):

1.將前端數(shù)據(jù)封裝成一個(gè)對(duì)象:

2.將對(duì)象轉(zhuǎn)化為JSON字符串:

3.后端獲取對(duì)象或?qū)傩裕?/p>

4.解析為Java對(duì)象:

2、從后端向前端傳遞數(shù)據(jù)

  1. 將Java對(duì)象轉(zhuǎn)化為JSON字符串:
    String s = JSON.toJSONString(student);
  2. 實(shí)例化一個(gè)PrintWrite對(duì)象,調(diào)用write方法向前端傳遞:
    PrintWriter writer = res.getWriter();
  3. 前端接收到后端的數(shù)據(jù):
    let data = xmlHttpRequest.responseText;
  4. 將JSON字符串解析為JS對(duì)象:
    et parse = JSON.parse(data);(拿到的是一個(gè)數(shù)組或者一個(gè)對(duì)象)

二、使用Ajax發(fā)起請(qǐng)求的方式

這一部分可看可不看,我主要是自己梳理一下代碼

1、使用GET方式向前端請(qǐng)求數(shù)據(jù)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function ajax1(){
            //以下是AJAX請(qǐng)求流程
            let xmlHttpRequest = new XMLHttpRequest();//1.創(chuàng)建XMLHttpRequest對(duì)象
            xmlHttpRequest.open("get","/javawebstudy2025_war_exploded/ajax1",true)//2.初始化請(qǐng)求,添加請(qǐng)求參數(shù)

            xmlHttpRequest.onreadystatechange=function(){//3.設(shè)置狀態(tài)監(jiān)聽回調(diào)
                if (xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){
                    let data = xmlHttpRequest.responseText;
                    console.log(data);
                    document.querySelector("#res").innerHTML=data;
                }
            }
            xmlHttpRequest.send();//4.發(fā)送請(qǐng)求
        }
    </script>
</head>
<body>
<h1>Ajax測試開始啦!</h1>
<div id="res" style="width: 300px;height: 200px;background: aliceblue;border:2px solid lightblue">
  僅更換內(nèi)容,不刷新頁面
</div>
<button onclick="ajax1()">更換</button>
<h2>版權(quán)信息</h2>
</body>
</html>

小羊碎碎念:

  1. xmlHttpRequest.open(“get”,“/javawebstudy2025_war_exploded/ajax1”,true),該方法的三個(gè)參數(shù)分別是:請(qǐng)求方法類型,url,異步請(qǐng)求。(異步請(qǐng)求不寫默認(rèn)為true)
  2. 異步請(qǐng)求:
@WebServlet("/ajax1")
public class TestAjax1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("我是來自后端的數(shù)據(jù)!");//后端向前端傳遞的數(shù)據(jù)
    }
}

小羊碎碎念:

  1. WebServlet 注解:用于注冊(cè) Servlet ,將 Servlet 類與 Web 容器(如 Tomcat)建立關(guān)聯(lián),讓容器能夠識(shí)別、加載并正確調(diào)用 Servlet 處理 HTTP 請(qǐng)求。
  2. 創(chuàng)建 Servlet 類的常見方式:
    繼承HttpServlet類(重寫doGet、doPost方法或者直接實(shí)現(xiàn)service方法也可以);
    繼承GenerricServlet類(重寫service方法);
    實(shí)現(xiàn)Servlet接口(實(shí)現(xiàn)所有抽象方法)。
  3. 實(shí)現(xiàn)一個(gè)接口必須實(shí)現(xiàn)他的抽象方法,否則定義該類為抽象類。

2、使用Get請(qǐng)求從前端向后端傳遞數(shù)據(jù)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function ajax2(){
            let xmlHttpRequest = new XMLHttpRequest();
            //獲取DOM對(duì)象,再獲取它的值
            let user = document.querySelector(".user").value;
            let pwd = document.querySelector(".pwd").value;
            xmlHttpRequest.open('get','/javawebstudy2025_war_exploded/ajax2?name='+user+'&password='+pwd);
            // 異步請(qǐng)求不寫默認(rèn)是true
            xmlHttpRequest.onreadystatechange=function(){
                if (xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){
                    let data = xmlHttpRequest.responseText;
                    document.querySelector(".res").innerHTML=data;
                }
            }
            xmlHttpRequest.send();
        }
    </script>
</head>
<body>
<div class="res" style="width: 200px;height: 100px; border:lightskyblue 2px solid">
    用戶名和密碼是什么?
</div>
用戶名:<input type="text" class="user">

密碼:<input type="text" class="pwd">

<button onclick="ajax2()">提交</button>
</body>
</html>
@WebServlet("/ajax2")
public class TestAjax2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        writer.write("用戶名是"+name+",密碼是"+password+"!");
    }
}

三、主要思想代碼示例

首先,要明確是從前端向后端傳數(shù)據(jù)還是從后端向前端傳數(shù)據(jù)。
第二,數(shù)據(jù)在前后端之間以JSON字符串的形式進(jìn)行傳遞。那就涉及到JSON字符串的轉(zhuǎn)換與解析

1、獲取DOM對(duì)象、定義全局變量、初始化

let tabObj = document.getElementById("tab")
let sname = document.getElementById("sname");
let ssex = document.getElementById("ssex");
let sage = document.getElementById("sage");
let user = document.getElementById("user");
let pwd = document.getElementById("pwd");
let jsonData;
let indexc;
let id;

window.onload = function () {
    ajaxGetData();
}

function ajaxGetData() {
    let xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.open("get", "/javawebstudy2025_war_exploded/Do?method=selectDo", true);
    xmlHttpRequest.onreadystatechange = function () {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            let data = xmlHttpRequest.responseText;
            jsonData = JSON.parse(data);
            let maxIndex = jsonData[jsonData.length - 1].id + 1;
            initData("tab");
        }
    }
    xmlHttpRequest.send();
}

2、從前端向后端傳數(shù)據(jù)

(1)校驗(yàn)管理員

/**
 * 6、校驗(yàn)管理員、
 * 關(guān)于傳參選擇普通鍵值對(duì)還是JSON字符串:
 * 簡單數(shù)據(jù)用普通鍵值對(duì),直觀簡潔,在 URL拼接或傳統(tǒng)表單提交時(shí)很方便,后端解析也容易。
 * 而像實(shí)體類這種包含多個(gè)屬性、結(jié)構(gòu)較復(fù)雜的數(shù)據(jù),JSON 字符串能更好呈現(xiàn)其完整結(jié)構(gòu),方便前后端處理和交互
 * 這里測試過了,兩種方法都是可以的
 */
function isAdmin() {
    let xmlHttpRequest = new XMLHttpRequest();

    let newData={
        "admin":user.value,
        "password":pwd.value
    }
    let s = encodeURIComponent(JSON.stringify(newData));
    xmlHttpRequest.open("get", "/javawebstudy2025_war_exploded/Do?method=isAdminDo&Data="+s, true);
    /*let admin=user.value
    let password=pwd.value
    xmlHttpRequest.open("get", "/javawebstudy2025_war_exploded/Do?method=isAdminDo&admin="+admin+"&password="+password, true);*/
    xmlHttpRequest.onreadystatechange = function () {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            let data = xmlHttpRequest.responseText;
            let parse = JSON.parse(data);
            if(parse.msg=="success"){
                //前端中==就可以比較兩個(gè)字符串,而Java中需要用equals比較兩個(gè)對(duì)象是否相等,==比較兩個(gè)對(duì)象是否是同一個(gè)對(duì)象
                window.location.href="showList copy 2.html" rel="external nofollow" 
            }else{
                alert("用戶名或密碼錯(cuò)誤,請(qǐng)重試")
            }
        }
    }
    xmlHttpRequest.send();
}
    /**
     * 邏輯2:登錄
     *
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    public void isAdminDo(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        String data = servletRequest.getParameter("Data");
        JSONObject jsonObject = JSONObject.parseObject(data);
        String admin = jsonObject.getString("admin");
        String password = jsonObject.getString("password");
       /* String admin = servletRequest.getParameter("admin");
        String password = servletRequest.getParameter("password");*/

        StudentImplService studentImplService = new StudentImplService();
        Boolean login = studentImplService.isAdminService(admin, password);
//        System.out.println("login = " + login);
        PrintWriter writer = servletResponse.getWriter();

        if(login!=null){
//            HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
//            servletResponse1.sendRedirect("showList copy 2.html");
          //  Result result = new Result(1,"success",null);
            writer.write(JSON.toJSONString(Result.success()));
        }else{
            //return Result.error("登陸失敗");
          writer.write(JSON.toJSONString(Result.error("登錄失敗")));
//            writer.write(333);
        }

    }

(2)添加

/**
 * 2、添加數(shù)據(jù)
 * @returns
 */
function addData() {
    var maxIndex = jsonData[jsonData.length - 1].id + 1
    if (sname.value == "" || ssex.value == "" || sage.value == "") {
        alert("數(shù)據(jù)不完整")
        return false;
    }
    let newData = {
        "id": maxIndex,
        "sname": sname.value,
        "ssex": ssex.value,
        "sage": sage.value,
    }
    let jsonStr = encodeURIComponent(JSON.stringify(newData));
    // let jsonStr = JSON.stringify(newData);
    // alert(jsonStr)
    let xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.open("get", "/javawebstudy2025_war_exploded/Do?method=addDo&jsondata=" + jsonStr, true);
    xmlHttpRequest.onreadystatechange = function () {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            let data = xmlHttpRequest.responseText;
            ajaxGetData();
        }
    }
    xmlHttpRequest.send();
}
    /**
     * 邏輯4:添加
     *
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    public void addDo(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest req1 = (HttpServletRequest) servletRequest;
        HttpSession session = req1.getSession(false);
        PrintWriter writer = servletResponse.getWriter();

        String newStu = servletRequest.getParameter("jsondata");
        JSONObject jsonObject = JSONObject.parseObject(newStu);

        /*這里收參方式有問題,在前面已經(jīng)通過getParameter獲取到了jsondata,后面在取鍵時(shí)應(yīng)該.屬性名
        String sname = servletRequest.getParameter("sname");
        String ssex = servletRequest.getParameter("ssex");
        String sage = servletRequest.getParameter("sage");*/

        String sname = jsonObject.getString("sname");
        String ssex = jsonObject.getString("ssex");
        String sage = jsonObject.getString("sage");
        Student student = new Student(null, sname, ssex, sage);

        int add = studentImplService.insertService(student);
        if (add > 0) {
//            servletRequest.getRequestDispatcher("Do?method=selectDo").forward(servletRequest, servletResponse);

            HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
//            servletResponse1.sendRedirect("Do?method=selectDo");
        } else {
            System.out.println("添加失??!");
        }
    }

(3)實(shí)現(xiàn)更新

 * 5、更新數(shù)據(jù):將表格里的新數(shù)據(jù)又賦給json對(duì)象各屬性的值
 * 這個(gè)不用閉包
 */

function updateData1() {
    let xmlHttpRequest = new XMLHttpRequest();
    let newData = {
        "id": id,//這里我就使用的是全局變量,以后每次先點(diǎn)擊更新按鈕,id就會(huì)被重新賦值為當(dāng)前學(xué)號(hào)
        "sname": sname.value,
        "ssex": ssex.value,
        "sage": sage.value,
    }
    let s = encodeURIComponent(JSON.stringify(newData));
    xmlHttpRequest.open("get", "/javawebstudy2025_war_exploded/Do?method=updateDo&newStu=" + s, true);
    xmlHttpRequest.onreadystatechange = function () {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            ajaxGetData();
        }
    }
    xmlHttpRequest.send();
}
    /**
     * 邏輯6:真正實(shí)現(xiàn)更新
     * @param req
     * @param res
     * @throws ServletException
     * @throws IOException
     */
    public void updateDo(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        String newStu = req.getParameter("newStu");
        JSONObject jsonObject = JSONObject.parseObject(newStu);

        Integer id = jsonObject.getInteger("id");
        String sname = jsonObject.getString("sname");
        String ssex = jsonObject.getString("ssex");
        String sage = jsonObject.getString("sage");
        Student student = new Student(id, sname, ssex, sage);

        int update = studentImplService.updateService(student);
        if (update < 0) {
            System.out.println("更新失??!");
        }
    }
}

3、從后端向前端傳數(shù)據(jù)

(1)查詢數(shù)據(jù)

/**
 * 1、渲染json數(shù)據(jù),并且動(dòng)態(tài)生成表格
 */
function initData(tab) {
    // 清理原來的DOM結(jié)構(gòu)(不清理表頭)
    tabObj.innerHTML = "";

    for (let index = 0; index < jsonData.length; index++) {
        var trObj = document.createElement("tr")
        if (index % 2 == 0) {
            trObj.style.backgroundColor = "lightblue"http://偶數(shù)行是藍(lán)色
        }
        for (let pos = 0; pos < Object.keys(jsonData[0]).length + 2; pos++) {
            var tdObj = document.createElement("td")
            trObj.appendChild(tdObj)
        }
        let tdObjChildren = trObj.children;
        let m = 0;
        Object.keys(jsonData[index]).forEach(key => {
                tdObjChildren[m++].innerHTML = jsonData[index][key];
            }
        )
        let btnObj = document.createElement("button")
        btnObj.innerHTML = "刪除";
        btnObj.onclick = delDate(index);
        // tdObjChildren[4].appendChild(btnObj)
        tdObjChildren[Object.keys(jsonData[0]).length].appendChild(btnObj)

        let btnObj1 = document.createElement("button")
        btnObj1.innerHTML = "更新";
        btnObj1.onclick = updateData(jsonData[index].id)
        tdObjChildren[Object.keys(jsonData[0]).length + 1].appendChild(btnObj1)

        tabObj.appendChild(trObj)
    }
}
    /**
     * 邏輯1:渲染數(shù)據(jù)
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void selectDo(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest req1 = (HttpServletRequest) req;
        HttpSession session = req1.getSession(false);
        HttpServletResponse resp1 = (HttpServletResponse) resp;
        List<Student> allData = studentImplService.getAllService();
        String s = JSON.toJSONString(allData);
        PrintWriter writer = resp.getWriter();
        writer.write(s);
        //   req1.setAttribute("data", allData);
//        req1.getRequestDispatcher("ShowList1.jsp").forward(req1, resp1);

    }

(2)獲取一條數(shù)據(jù)

/**
 * 4、更新數(shù)據(jù):將json數(shù)據(jù)放在表格里
 */
function updateData(index) {
    let index1 = index//閉包函數(shù)寫法
    return function () {
        indexc = index1;//全局的indexc記錄了要修改的數(shù)據(jù)的下標(biāo)
        let xmlHttpRequest = new XMLHttpRequest();
        xmlHttpRequest.open("get", "/javawebstudy2025_war_exploded/Do?method=getOneDo&id=" + indexc, true);
        xmlHttpRequest.onreadystatechange = function () {
            if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
                let data = xmlHttpRequest.responseText;
               /* if(data.code==200 && data.msg=="success")
                {

                }*/
                let parse = JSON.parse(data);
                id = parse.id;//我將這里的id設(shè)置為全局變量,為了在真正實(shí)現(xiàn)更新時(shí)給“id”值
                // console.log(id);
                sname.value = parse.name//注意,這里返回了一條從數(shù)據(jù)庫里面查出來的數(shù)據(jù),你通過.屬性名時(shí)這里的屬性名是表中字段名
                ssex.value = parse.sex
                sage.value = parse.age
                // console.log(parse);
                ajaxGetData();
            }
        }
        xmlHttpRequest.send();
    }
}
    /**
     * 邏輯5:獲取一條數(shù)據(jù):服務(wù)器端渲染
     * @param req
     * @param res
     * @throws ServletException
     * @throws IOException
     */
    public void getOneDo(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        Student student = studentImplService.getOneService(id);
        String s = JSON.toJSONString(student);
        PrintWriter writer = res.getWriter();
        writer.write(s);
    }

(3)刪除一條數(shù)據(jù)

/**
 * 3、刪除數(shù)據(jù)
 * @param {*} index
 * @returns
 */
//也可以在調(diào)用處傳參jsonData[index].id,然后讓他等于index1,在地址里面?zhèn)鲄ndex1即可
function delDate(index) {
    let index1 = index;
    return function () {
        if (confirm("確認(rèn)刪除嗎?")) {
            let xmlHttpRequest = new XMLHttpRequest();
            xmlHttpRequest.open("get", "/javawebstudy2025_war_exploded/Do?method=delDo&id=" + jsonData[index1].id, true);
            xmlHttpRequest.onreadystatechange = function () {
                if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
                    // let data = xmlHttpRequest.responseText;
                    ajaxGetData();
                }
            }
            xmlHttpRequest.send();
        }
    }
}
    /**
     * 邏輯3;刪除
     *
     * @param req
     * @param res
     * @throws ServletException
     * @throws IOException
     */
    public void delDo(ServletRequest req, ServletResponse res) throws ServletException, IOException {
//        獲取刪除的那條記錄的主鍵ID
        String id = req.getParameter("id");
        System.out.println("id = " + id);
//        數(shù)據(jù)訪問層
        Integer idd = Integer.valueOf(id);
        int i = studentImplService.delService(idd);
        System.out.println("i = " + i);
        if (i > 0) {
//            req.getRequestDispatcher("/Do?method=selectDo").forward(req, res);
            HttpServletResponse servletResponse1 = (HttpServletResponse) res;
//            servletResponse1.sendRedirect("Do?method=selectDo");
        } else {
            System.out.println("刪除失??!");
        }
    }

4、數(shù)據(jù)訪問層展示

我的這個(gè)項(xiàng)目實(shí)現(xiàn)了數(shù)據(jù)的增刪查改與校驗(yàn)管理員(通過vscode中我那個(gè)純前端的項(xiàng)目改造的),分別寫了兩個(gè)實(shí)體類:學(xué)生類和管理員類,我也為他們分別寫了數(shù)據(jù)訪層。我記得當(dāng)時(shí)沒有寫管理員類,然后通過mybatis操作數(shù)據(jù)庫失敗了,所以定義管理員類是必要的。

package dao;
import moudle.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;

public interface StudentDao {
//    渲染數(shù)據(jù)
    @Select("select * from Student")
    List<Student> getAllDao();
//    刪除
    @Delete("delete from student where id=#{id}")
    int delDao(Integer id);
//    添加
    @Insert("insert into student values (null,#{name},#{sex},#{age})")
    int insertDao(Student student);
//    拿到一條數(shù)據(jù)
    @Select("select * from student where id=#{id}")
    Student getOneDao(Integer id);
//    更新
    @Update("update student set name=#{name},sex=#{sex},age=#{age} where id=#{id}")
    int updateDao(Student student);
//    分頁查詢
    @Select("select * from student limit #{start},#{pageSize}")
    List<Student> fenYeDao(@Param("start") Integer start,@Param("pageSize") Integer pageSize);
}
package dao;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface ManagerDao {
    @Select("select * from manager where admin=#{admin} and password=#{password}")
    Boolean isAdminDao(@Param("admin") String admin,@Param("password") String password);
}

5、分頁查詢前端代碼備份

這是一個(gè)jsp文件

<%@ page import="moudle.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="service.impl.StudentImplService" %>
<%--
  Created by IntelliJ IDEA.
  User: 34806
  Date: 2025/5/7
  Time: 10:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>學(xué)生信息列表展示</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"  rel="external nofollow" >
    <script src="https://cdn.staticfile.net/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.net/popper.js/1.15.0/umd/popper.min.js"></script>
    <script src="https://cdn.staticfile.net/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<%
    //    List<Student> data = (List<Student>) request.getAttribute("data");
    /**
     *     作用域問題:在 JSP 中,
     *     request.getAttribute("data") 獲取數(shù)據(jù),
     *     request 作用域僅在一次請(qǐng)求 - 響應(yīng)過程中有效。
     *     點(diǎn)擊下一頁是新請(qǐng)求,之前 request 作用域里的數(shù)據(jù)不會(huì)自動(dòng)帶到新請(qǐng)求中。
     *     若沒有重新設(shè)置 data 到新 request 作用域,就獲取不到。
     */
    StudentImplService studentImplService1 = new StudentImplService();
    List<Student> data = studentImplService1.getAllService();

//    1.計(jì)算有多少條數(shù)據(jù)
    int totalCount = data.size();
//    2.設(shè)置每一頁有幾條數(shù)據(jù)
    int pageSize = 3;
//    3.計(jì)算有多少頁
    int pageCount = (int) (Math.ceil(totalCount * 1.0 / pageSize));
//    4.獲取當(dāng)前頁
    int curPage = request.getParameter("curPage") == null ?
            1 : Integer.valueOf(request.getParameter("curPage"));
//    計(jì)算偏移值
    int offSet = (curPage - 1) * 3;
//    5.獲取當(dāng)前頁的數(shù)據(jù)
    StudentImplService studentImplService = new StudentImplService();
    List<Student> students = studentImplService.fenYeService(offSet, pageSize);
%>
<%--你依然保持在線!--%>
<a href='/javawebstudy2025_war_exploded/logout'>退出</a>
<table class="table">
    <thead class="thead-dark">
    <tr>
        <th>學(xué)號(hào)</th>
        <th>姓名</th>
        <th>性別</th>
        <th>年齡</th>
        <th>操作1</th>
        <th>操作2</th>
    </tr>
    </thead>
    <tbody>
    <%
        for (int i = 0; i < students.size(); i++) {
    %>
    <tr>
        <td>
            <%=students.get(i).getId()%>
        </td>
        <td>
            <%=students.get(i).getName()%>
        </td>
        <td>
            <%=students.get(i).getSex()%>
        </td>
        <td>
            <%=students.get(i).getAge()%>
        </td>
        <td>
            <a href="/javawebstudy2025_war_exploded/Do?method=delDo&id=<%=students.get(i).getId()%>" rel="external nofollow" 
               onclick="if(confirm('確認(rèn)刪除嗎?')) return true;return false;">刪除</a>
        </td>
        <td>
            <a href="/javawebstudy2025_war_exploded/Do?method=getOneDo&id=<%=students.get(i).getId()%>" rel="external nofollow" >更新</a>
        </td>
    </tr>
    <%
        }

    %>
    <%
        if (curPage == 1) {

    %>
    <tr>
        <td>首頁</td>
        <td>上一頁</td>
        <td><a href="ShowList1.jsp?curPage=<%=curPage+1%>" rel="external nofollow"  rel="external nofollow" >下一頁</a></td>
        <td><a href="ShowList1.jsp?curPage=<%=pageCount%>" rel="external nofollow"  rel="external nofollow" >尾頁</a></td>
    </tr>
    <%
    } else if (curPage == pageCount) {
    %>
    <tr>
        <td><a href="ShowList1.jsp?curPage=1" rel="external nofollow"  rel="external nofollow" >首頁</a></td>
        <td><a href="ShowList1.jsp?curPage=<%=curPage-1%>" rel="external nofollow"  rel="external nofollow" >上一頁</a></td>
        <td>下一頁</td>
        <td>尾頁</td>
    </tr>
    <%
    } else {
    %>
    <tr>
        <td><a href="ShowList1.jsp?curPage=1" rel="external nofollow"  rel="external nofollow" >首頁</a></td>
        <td><a href="ShowList1.jsp?curPage=<%=curPage-1%>" rel="external nofollow"  rel="external nofollow" >上一頁</a></td>
        <td><a href="ShowList1.jsp?curPage=<%=curPage+1%>" rel="external nofollow"  rel="external nofollow" >下一頁</a></td>
        <td><a href="ShowList1.jsp?curPage=<%=pageCount%>" rel="external nofollow"  rel="external nofollow" >尾頁</a></td>
    </tr>
    <%
        }
    %>
    </tbody>
</table>

<button style='padding: 10px 20px;display: block; margin: 0 auto;'>
    <a href="/javawebstudy2025_war_exploded/add.html" rel="external nofollow" >添加</a>
</button>

</body>
</html>

總結(jié) 

到此這篇關(guān)于使用Ajax從前端向后端發(fā)起請(qǐng)求的文章就介紹到這了,更多相關(guān)Ajax從前端向后端發(fā)起請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論