【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了,请看【jquery】使用ajax请求后端数据局部刷新小demo
他的路径是localhost:8080/testServlet 于是报404

正解:

【jquery】使用ajax请求后端数据局部刷新小demo