相关技巧
主页 > 网络编程 > 相关技巧 >

用自写的jQuery库+Ajax实现了省市联动功能

2025-07-11 | 佚名 | 点击:

1. 省市联动:

在网页上,选择对应的省份之后,动态的关联出该省份对应的市。选择对应的市之后,动态地关联出城市对应的区。

2. 设计数据库表

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

t_area (区域表)

id(PK-自增)     code      name        pcode

---------------------------------------------

1               001      河北省        null

2               002      河南省        null

3               003      石家庄        001

4               004      邯郸     001

5               005      郑州     002

6               006      洛阳     002

7               007      江苏       null

8               008      南京       007

 

 

将全国所有的省、市、区、县等信息都存储到一张表当中。

采用的存储方式实际上是code pcode形势。

3. 这里只是一个模拟,所以建的数据库是不完整的,想要完整的数据库,可以去网上找。

4. 上代码

(1)自写的jQquery库

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

function jQuery(selector){ // selector可能是#id,也可以是其他的选择器,例如类选择器:.class

    if(typeof selector == "string"){

        if (selector.charAt(0) == '#') {

            domObj = document.getElementById(selector.substring(1));

            return new jQuery();

        }

    }

    if(typeof selector == "function"){

        window.onload = selector;

    }

    this.html = function(htmlStr){

        domObj.innerHTML = htmlStr;

    }

    this.click = function(fun){

        domObj.onclick = fun;

    }

    this.val = function(v){

        if (v == undefined) {

            return domObj.value;

        }else{

            domObj.value = v;

        }

    }

    this.change = function(fun){

        domObj.onchange = fun;

    }

    // 静态的方法:发送ajax请求

    jQuery.ajax = function(jsonArgs){

        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function(){

            if (this.readyState == 4) {

                if (this.status == 200) {

                    var jsonObj = JSON.parse(this.responseText);

                    jsonArgs.success(jsonObj);

                }

            }

        }

        if (jsonArgs.type.toUpperCase() == "POST") {

            xhr.open("POST",jsonArgs.url,jsonArgs.async);

            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

            xhr.send(jsonArgs.data);

        }

        if (jsonArgs.type.toUpperCase() == "GET") {

            xhr.open("GET",jsonArgs.url + "?" + jsonArgs.data,jsonArgs.async);

            xhr.send();

        }

    }

}

$=jQuery;

(2)html文件(Ajax请求)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>用ajax实现省市联动</title>

</head>

<body>

<!--引入自己编写的jQuery库-->

<script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js"></script>

<!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->

<script type="text/javascript">

$(function(){

    // 发送ajax请求,获取所有的省份,省份的pcode是null

    $.ajax({

        type: "get",

        url : "/ajax/listArea",

        data : "t=" + new Date().getTime(),

        async : true,

        success:function(jsonArr){

            var html = "<option value=\"\">--请选择省份--</option>";

            for (var i = 0; i < jsonArr.length; i++) {

                var area = jsonArr[i];

                html += "<option value=\""+area.code+"\">"+area.name+"</option>"

            }

            $("#province").html(html)

        }

    })

    // 只要change发生,就发送ajax请求

    $("#province").change(function(){

        $.ajax({

            type: "get",

            url : "/ajax/listArea",

            data : "t=" + new Date().getTime()+ "&pcode="+this.value,

            async : true,

            success:function(jsonArr){

                var html = "<option value=\"\">--请选择市--</option>";

                for (var i = 0; i < jsonArr.length; i++) {

                    var area = jsonArr[i];

                    html += "<option value=\""+area.code+"\">"+area.name+"</option>"

                }

                $("#city").html(html)

            }

        })

    })

})

</script>

<select id="province"></select>

<select id="city"></select>

</body>

</html>

(3)servlet文件(后端)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

package com.bjpowernode.ajax.servlet;

 

import com.alibaba.fastjson.JSON;

import com.bjpowernode.ajax.bean.Area;

import jakarta.servlet.ServletException;

import jakarta.servlet.annotation.WebServlet;

import jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;

 

import java.io.IOException;

import java.sql.*;

import java.util.ArrayList;

 

/**

 * 动态获取所有的省份

 */

@WebServlet("/listArea")

public class ListAreaServlet extends HttpServlet {

    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 连接数据库,获取所有的对应区域,最终响应一个JSON格式的字符串给WEB前端

        Connection conn = null;

        PreparedStatement ps = null;

        ResultSet rs= null;

        ArrayList<Area> areas = new ArrayList<>();

        String pcode = request.getParameter("pcode");

        String sql;

        try {

            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=UTF-8";

            String user = "root";

            String password = "1234";

            conn = DriverManager.getConnection(url,user,password);

            if (pcode == null){

                sql = "select code,name from t_area where pcode is null";

                ps = conn.prepareStatement(sql);

            }else{

                sql = "select code,name from t_area where pcode = ?";

                ps = conn.prepareStatement(sql);

                ps.setString(1,pcode);

            }

            rs = ps.executeQuery();

            while (rs.next()) {

                String code = rs.getString("code");

                String name = rs.getString("name");

                Area area = new Area(code, name);

                areas.add(area);

            }

        } catch (ClassNotFoundException e) {

            throw new RuntimeException(e);

        } catch (SQLException e) {

            throw new RuntimeException(e);

        } finally{

            if (rs != null) {

                try {

                    rs.close();

                } catch (SQLException e) {

                    throw new RuntimeException(e);

                }

            }

            if (ps != null) {

                try {

                    ps.close();

                } catch (SQLException e) {

                    throw new RuntimeException(e);

                }

            }

            if (conn != null) {

                try {

                    conn.close();

                } catch (SQLException e) {

                    throw new RuntimeException(e);

                }

            }

        }

        response.setContentType("text/html,charset=UTF-8");

        String json = JSON.toJSONString(areas);

        response.getWriter().print(json);

    }

 

}

5. 展示效果

原文链接:
相关文章
最新更新