标签:init jquery function set pre get 注释 element 默认
?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PHP+ajax实现二级联动</title> </head> <body> <select id="province"> <option value="0">请选择省份</option> <option value="1">北京</option> <option value="2">河北</option> <option value="3">山东</option> </select> <select id="city"> <option value="0">请选择城市</option> </select> </body> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(function(){ $("#province").change(function(){ var province = $(this).val(); // 获取province的value值 if(province == 0){ // province为0的时候停止;否则 return; }else{ var url = ‘demo.php‘; $.ajax({ url: url, // php的url路径 type: ‘post‘, data: {province:province}, dataType: ‘json‘, success: function(res) { if(res.code == 200){ var option = ‘<option>请选择城市</option>‘; var list = res.list; for (var i = 0; i < list.length; i++) { // 循环返回的值(城市) option += "<option>" + list[i] + "</option>"; } }else{ var option = ‘<option>请选择城市</option>‘; // 请求失败(默认) } $("#city").html(option); // js刷新第二个下拉框的值 } }) } }) }) </script> </html>接下来为PHP代码,注释已表明;?
<?php $province = $_POST[‘province‘]; // 获取ajax传来的值 $list[‘1‘] = [‘朝阳‘, ‘海淀‘, ‘西城‘]; $list[‘2‘] = [‘保定‘, ‘唐山‘, ‘邯郸‘]; $list[‘3‘] = [‘济南‘, ‘菏泽‘, ‘日照‘]; if($list[$province]){ // 数组存在值的情况下 echo json_encode([‘code‘=>200, ‘list‘=>$list[$province]]); // 200成功,$list[$province]传递相应的数据 }else{ echo json_encode([‘code‘=>500]); }
PHP+ajax实现二级联动
原文地址:https://www.cnblogs.com/xiaocong-PHP-12685/p/10569772.html