標籤:
目標
需要的是在選擇第一個select下拉式清單後,將選擇的內容傳送到PHP頁面。在PHP頁面中通過查詢數庫,得到第二個select需要顯示的option的值,並在select中顯示。
方案
1 利用ajax上傳資料到PHP,由於利用了smarty模板技術,可以直接給模板中的變數賦值,這樣就可以不用通過ajax接收返回值再經過處理輸出了。由於這個PHP頁面沒有包含在其他PHP頁面裡,是獨立的。這樣就造成無法賦值。
2 通過ajax接收返回值,這裡的返回值就是以上資料庫查詢的結果。 通過json_encode()將其轉化為json格式,然後輸出。 js中將responseText字串轉化為json格式——JSON.parse()函數實現。 遍曆數組,並添加option給select。
本次使用的是方案2
部分代碼
JS代碼:
function get_value(form){var scid=sub_class.value;//運算類型號//---------------------------------------//使用ajax發送選中的運算類var url = "query_subject.php?scid="+scid;xmlhttp.onreadystatechange = Content;//var url = "query_subject.php?";xmlhttp.open("GET",url,true);xmlhttp.send(null);//---------------------------------------function Content(){if(xmlhttp.readyState==4){if(xmlhttp.status==200){var sel=document.getElementById("sub_name");var rst=JSON.parse(xmlhttp.responseText);//將字串轉化為數組for(var i=0; i<rst.length; i++){var opt=document.createElement('option');opt.value=rst[i].sid;opt.text=rst[i].s_name;try { sel.add(opt,null); // standards compliant } catch(ex) { sel.add(opt); // IE only }}}else{alert("你請求的分頁錯誤");}}}}
PHP代碼:
?phpheader ( "Content-type: text/html; charset=UTF-8" ); //設定檔案編碼格式require_once("system/system.inc.php"); //包含設定檔$scid=$_GET['scid'];$rst=null;if($scid){$sql="select sid, s_name from subject where scid='$scid'";$rst=$admindb->ExecSQL($sql, $conn);}echo(json_encode($rst));?>
html+js+PHP(使用了smarty模板技術)+mysql實現二級動態下拉式清單(select)