三级联动及优化

  今天我们通过 Memcache 优化三级联动

  第一步 , 我们需要建立一个数据库 test , 数据库中有一个表 region,

  第二步 , 写代码

   下面数据库请求的过程  index.php

<?php
    // 数据库连接
    $mysqli = new mysqli("127.0.0.1","root","","test");
    // 设置编码方式
    $mysqli->set_charset("utf8");
    // 逻辑控制语句
    $pid = isset($_GET["pid"]) ? $_GET['pid'] : 0;
    // 实例化  Memcache优化
    $mem = new Memcache();
    $mem->connect("127.0.0.1",11211);
    $allarea = $mem->get("area_" .$pid);
    if (empty($allarea)) {
        // 查询数据 
        $sql = "select * from region where pid=" . $pid;
        // 发送sql语句
        $result = mysqli_query($mysqli,$sql);
        // 处理查询结果
        while($area = mysqli_fetch_assoc($result)){
            $allarea[] = $area;
        };
        // 将查询到的数据放到memcache中
        $mem->set("area_".$pid,$allarea);
    }
    if ($pid) {
        exit(json_encode($allarea));
    }
    include("area.html");
?>

     area.html 中的内容

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>三级联动</title>
    <link rel="stylesheet" href="">
</head>
<body>
    <div class="choose">
        <label>省份</label>
        <select class="select" id="province" next-level="city">
            <option value="">请选择</option>
            <?php foreach($allarea as $val) {?>
            <option value="<?php echo $val['id'] ?>"><?php echo $val['name']; ?></option>}
            <?php } ?>
        </select>
        <label>地市</label>
        <select class="select" id="city" next-level="area">
            <option value="">请选择</option>
        </select>
        <label>区县</label>
        <select id="area">
            <option value="">请选择</option>
        </select>
    </div>
</body>
</html>
<script src="js/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
    $(".select").change(function() {
        var nextlevel = $(this).attr("next-level");
        var val = $(this).val();
        if (val == "") {
            return false;
        }
        // 发起ajax请求
        $.ajax({
            url:"index.php", // 请求服务器的地址
            type:"get",    
            data:{pid:val},        // 提交的数据
            dataType:"JSON",     // 预期返回的数据格式
            success:function(res){ // 请求成功后的函数
                // console.log(res);
                // var optionhtml = '<option value="">请选择</option>';
                var optionhtml = '';
                // 循环 each 
                $.each(res,function(key,val){
                    optionhtml += '<option value="'+val.id+'">'+val.name+'</option>'
                })
                
                // html 会覆盖前面的内容
                // $(".select:eq(1)").html(optionhtml);

                //  append 追加 再追加之前先删除除了第一个以外的前面的内容
                $("#" +nextlevel+ " option:not(:first)").remove();
                $("#" +nextlevel).append(optionhtml);
            }
        })
    });    
</script>

    使用Memcache临时性键值储存,减轻了mysql数据库的负担,减少了ajax的请求,同时也要注意memcache与mqsql 之间并不是对立的, 而是互补的关系.

猜你喜欢

转载自www.cnblogs.com/461770539-qq/p/9434957.html