Ajax+php實現商品分類三級聯動_AJAX相關

來源:互聯網
上載者:User

當頁面載入時,利用ajax非同步向後台請求資料,載入一級商品類別,當選擇一級商品時載入二級商品,選擇二級商品載入三級商品。 

實現:
1、當拿到資料後載入pid為0的商品,並動態建立option將商品追加到一級菜單中,並設定value值
2、當選擇一級商品時載入pid=當前id的商品,並建立option將商品追加到二級菜單中,並設定value值
3、當選擇二級商品時載入pid=當前id的商品,並建立option將商品追加到三級菜單中,並設定value值 

頁面效果: 

$(function(){  //請求路徑  var url="03goods.php";  //option預設內容  var option="<option value='0'>未選擇</option>";  //擷取jq對象  var $sel1=$(".sel1");  var $sel2=$(".sel2");  var $sel3=$(".sel3");  //自動產生一個<option>元素  function createOption(value,text){  var $option=$("<option></option>");  $option.attr("value",value);  $option.text(text);  return $option;  }  //載入資料  function ajaxSelect($select,id){  //get請求  $.get(url,{"pid":id},function(data){   $select.html(option);   for(var k in data ){   $select.append(createOption(data[k].id,data[k].name));   }  },"json");  }  //自動載入第一個下拉式功能表  ajaxSelect($sel1,"0");  //選擇第一個下拉式功能表時載入第二個  $sel1.change(function(){  var id=$sel1.val();  if(id=="0"){   $sel2.html(option);   $sel3.html(option);  }else{   ajaxSelect($sel2,id);  }  });  //選擇第二個下拉式功能表時載入第三個  $sel2.change(function(){  var $id=$sel2.val();  if($id=="0"){   $sel3.html(option);  }else{   ajaxSelect($sel3,$id);  }  }); });

後台代碼: 

<?php header('Content-Type:text/html; charset=utf-8'); //資料 $arr=array( //array(分類id,分類名,分類的父id) array('id'=>'1','name'=>'數位產品','pid'=>'0'), array('id'=>'2','name'=>'家電','pid'=>'0'), array('id'=>'3','name'=>'書籍','pid'=>'0'), array('id'=>'4','name'=>'服裝','pid'=>'0'), array('id'=>'5','name'=>'手機','pid'=>'1'), array('id'=>'6','name'=>'筆記本','pid'=>'1'), array('id'=>'7','name'=>'平板電腦','pid'=>'1'), array('id'=>'8','name'=>'智能手機','pid'=>'5'), array('id'=>'9','name'=>'功能機','pid'=>'5'), array('id'=>'10','name'=>'電視機','pid'=>'2'), array('id'=>'11','name'=>'電冰箱','pid'=>'2'), array('id'=>'12','name'=>'智能電視','pid'=>'10'), array('id'=>'13','name'=>'編程書籍','pid'=>'3'), array('id'=>'14','name'=>'JavaScript','pid'=>'13'), ); //擷取指定分類的商品 function getByPid($arr,$pid){ $result=array(); foreach($arr as $v){  if($v['pid']==$pid){  $result[]=$v;  } } return $result; } //擷取請求參數 $pid=isset($_GET['pid'])?$_GET['pid']:'0'; $result=getByPid($arr,$pid); //輸出json資料 echo json_encode($result);?>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.