本文實(shí)例講述了PHP+ajax實(shí)現(xiàn)二級(jí)聯(lián)動(dòng)菜單功能。分享給大家供大家參考,具體如下:
如何實(shí)現(xiàn)二級(jí)聯(lián)動(dòng)
工作原理
二級(jí)聯(lián)動(dòng)在開發(fā)中是比較常見的一個(gè)技術(shù)點(diǎn),它主要運(yùn)用了JS的局部刷新技術(shù)ajax,不同于一般頁面全局刷新,它只會(huì)刷新我們需要改變值的地方,我們首先看下它的工作流程。
HTML代碼
html> head> title>www.jb51.net 二級(jí)聯(lián)動(dòng)/title> meta http-equiv="Content-Type" content="text/html;charset=utf8"> script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js">/script> style> #area-box{width:500px;height:400px;margin:0 auto;border:0px solid #dddddd;text-align:center;} .area-select{width:200px;height:30px;margin-top:30px;margin-left:30px;} /style> head> body> div id="area-box"> select class="area-select" id='address'> option value="0">請(qǐng)選擇省份/option> option value="1">四川/option> option value="2">河北/option> option value="3">湖南/option> /select> select class="area-select" id="city"> option>請(qǐng)選擇城市/option> /select> /div> script> $(function(){ //初始化數(shù)據(jù) var url = 'address.php'; //后臺(tái)地址 $("#address").change(function(){ //監(jiān)聽下拉列表的change事件 var address = $(this).val(); //獲取下拉列表選中的值 //發(fā)送一個(gè)post請(qǐng)求 $.ajax({ type:'post', url:url, data:{key:address}, dataType:'json', success:function(data){ //請(qǐng)求成功回調(diào)函數(shù) var status = data.status; //獲取返回值 var address = data.data; if(status == 200){ //判斷狀態(tài)碼,200為成功 var option = ''; for(var i=0;iaddress.length;i++){ //循環(huán)獲取返回值,并組裝成html代碼 option +='option>'+address[i]+'/option>'; } }else{ var option = 'option>請(qǐng)選擇城市/option>'; //默認(rèn)值 } $("#city").html(option); //js刷新第二個(gè)下拉框的值 }, }); }); }); /script> /body>
PHP代碼
?php $key = $_POST['key']; //獲取值 $address[1] = array('成都','綿陽','德陽'); $address[2] = array('石家莊','唐山','秦皇島'); $address[3] = array('長(zhǎng)沙','株洲','湘潭'); if(!empty($address[$key])){ //有值,組裝數(shù)據(jù) $result['status'] = 200; $result['data'] = $address[$key]; }else{ //無值,返回狀態(tài)碼220 $result['status'] = 220; } echo json_encode($result); //返回JSON數(shù)據(jù) ?>
運(yùn)行效果:
其實(shí)三級(jí)聯(lián)動(dòng)和二級(jí)聯(lián)動(dòng)的原理都是一樣的,只是在其基礎(chǔ)上在重復(fù)一次而已
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP+ajax技巧與應(yīng)用小結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP基本語法入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:白銀 廊坊 辛集 太原 衡陽 崇左 綏化 鄂州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP+ajax實(shí)現(xiàn)二級(jí)聯(lián)動(dòng)菜單功能示例》,本文關(guān)鍵詞 PHP+ajax,實(shí)現(xiàn),二級(jí),聯(lián)動(dòng),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。