【jquery】使用ajax請求後端數據局部刷新小demo

記一次艱難的jquery旅行

題記:奶奶的,今天下午折騰了很久的用jquery中的ajax請求後端,總是在url出現bug,idea總出404,搞了一會,參考別人博客,把那個url寫成下面這種形式竟然成功訪問,ojbk。還準備請教在外工作的學長,後來還是自己解決了,爽歪歪。


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%String path=request.getContextPath();%>
<html>
<head>
    <title>myfile</title>
    <script type="text/javascript" src="./js/jquery-3.4.0.js"></script>
    <script>
        $(function () {
            $("input:radio").click(function () {
                //動作出發後相應時間
                console.log("進入點擊事件");
                var val = $('input:radio[name="dept"]:checked').val();
                console.log(val);
                $.ajax({
                    url: "http://localhost:8080/myproject/testServlet", //這個我之前寫的是testServlet,一直報404.我後來又試了試,完全沒問題用testservlet。這就怪了。只是我又重新把包和位置model的位置又刪除了,構建了一下,所以做事情一定要有耐心,仔細排錯
                    type:"post",
                    data:{
                        dept:val
                    },
                    success:function (result) {
                        console.log(result);
                        var data ="<h5>課程如下:</h5>"+ result;
                        $("#bookList").html(data);
                    }
                });
            });
        });
    </script>
</head>

<body>

    <form>
        <h2>請輸入網址名和網址</h2>
        <input type="radio" name="dept" value="1" />計算機系
        <input type="radio" name="dept" value="2"/>工商管理序員
        <input type="radio" name="dept" value="3"/>心裏系<br>
        <div id="bookList"></div>
    </form>
</body>
</html>

後端測試

package com.yzz.test;

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;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.Arrays;

@WebServlet("/testServlet")
public class TestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("請求到此處");
        int deptId = Integer.parseInt(request.getParameter("dept"));
        PrintWriter out = response.getWriter();
        String[] dept1 = {"java","c++","c"};
        String[] dept2 = {"111","222","333"};
        String[] dept3 = {"aaa","bbb","cccc"};

        switch (deptId) {
            case 1: out.write(Arrays.toString(dept1));break;
            case 2: out.write(Arrays.toString(dept2));break;
            case 3: out.write(Arrays.toString(dept3));break;
        }
    }
}

排錯

終於知道自己的bug了,請看alt
他的路徑是localhost:8080/testServlet 於是報404

正解:

file2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章