首先是 Ajax.php檔案:
這個檔案我覺著就是接收資料處理資料的
| 代碼如下 |
複製代碼 |
<?php mysql_connect("localhost","root",""); mysql_select_db("aaa"); mysql_query("set names 'UTF8'"); |
上面的這些代碼 不用我說都知道是串連資料庫的
| 代碼如下 |
複製代碼 |
//select 語句 1.//$q=mysql_query("select * from `newstype` where `kid`='".$_POST['id']."'"); 2.$sql="select * from `newstype` where `kid`='".$_POST['id']."'"; $q=mysql_query($sql); |
上面的1和2的選項是因為 我寫了一遍select語句出現報錯了 然後我就又寫了一遍 結果兩個都對了 1 是注釋掉了
if(mysql_num_rows($q)!=0){ 判斷尋找的語句的個數 如果是0的話就代表下面沒有分支了 就不會顯示了
//記住在$_POST[]加()這是我出現的錯誤
| 代碼如下 |
複製代碼 |
| echo "<select id='s".($_POST['num']+1)."' onchange='fun(".($_POST['num']+1).")'>"; |
輸出一個select選擇框會添加到後來最終顯示的頁面的div裡面 後面會做介紹
| 代碼如下 |
複製代碼 |
while($rs=mysql_fetch_array($q)){ echo"<option value=".$rs['id'].">".$rs['name']."</option>";select裡面的option選項 value的值一定要給 因為我們要按照這個尋找語句 } echo "</select>"; echo "<div id='list".($_POST['num']+1)."'></div>";因為做的是無限極聯動 後面還要輸出一個div的框 用來盛下一個的select框 } ?> |
--------------------------------------------------------------------------------
下面的是Ajax.js檔案var xmlhttp;定義一個變數
| 代碼如下 |
複製代碼 |
function createxml(){這個部分主要是用來判斷瀏覽器 if(window.XMLHttpRequest){ XMLHttpRequest是javascript裡面內建的屬性 具體的作用 大家自己去翻手冊 xmlhttp=new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); } } function fun(n){ 這個方法是展示頁中 select onchange事件調用 createxml(); var id=document.getElementById("s"+n).value; 是選取對應的id的select裡面的value值 就是我們上面說道的資料庫中的ID欄位 xmlhttp.open("post","Ajax.php",true); 開啟請求 xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //id之後還有一個+ xmlhttp.send("id="+id+"&num="+n); 發送請求 擷取這個id的值 和 n的值 並且分別賦值給 id 和 num xmlhttp.onreadystatechange=function(){stylefun(n)}; 觸發onreadystatechange調用stylefun(n)方法 並且設定n參數 } function stylefun(n){ if(xmlhttp.readyState==4 && xmlhttp.status==200){已經接受完成之後 把獲得的text賦值給對應id的div標籤裡面 //innerHTML 記住html是大寫 document.getElementById("list"+n).innerHTML=xmlhttp.responseText; } } |
--------------------------------------------------------------------------------
下面是展示頁面liandong.php(原諒我起名字的時候都是很簡單的思維)
| 代碼如下 |
複製代碼 |
<?php mysql_connect("localhost","root","")or die("連結資料庫失敗"); mysql_select_db("aaa"); mysql_query("set names'UTF8'"); $sql="select * from `newstype` where `kid` = 0";先尋找最初的根目錄類型 $query=mysql_query($sql); while($rs=mysql_fetch_array($query)){ $arr[]=$rs; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="Ajax.js"></script> </head> <body> <!--無限極聯動--> <select id="s1" onchange="fun(1)"> <?php foreach($arr as $v){ echo "<option value='".$v['id']."'>".$v['name']."</option>"; } ?> </select> <div id="list1"> </div> </body> </html> |