2013-03-06 71 views
0

我有三個下拉菜單。基於在第一個下拉列表中選擇的選項,我使用javascript填充第二個下拉列表。用查詢結果填充第三個下拉列表

第一個下拉

<select id="continent" onchange="secondMenu(this,'country')" > 
<option value="1">Asia</option> 
<option value="2">Europe</option 
</select> 

第二個下拉

<select id="country" > 
</select> 

第三下拉

<select id="population" > 
</select> 

我的腳本

<script> 
     function secondMenu(ddl1,ddl2){ 
    var as=new Array('Japan','China'); 
    var eu=new Array('Germany','France'); 
switch (ddl1.value) { 
     case 1: 
      document.getElementById(ddl2).options.length = 0; 
      for (i = 0; i < as.length; i++) { 
       createOption(document.getElementById(ddl2), as[i], as[i]); 
      } 
      break; 
     case 2: 
      document.getElementById(ddl2).options.length = 0; 
     for (i = 0; i < eu.length; i++) { 
      createOption(document.getElementById(ddl2), eu[i], eu[i]); 
      } 
      break; 

    } 
    function createOption(ddl, text, value) { 
    var opt = document.createElement('option'); 
    opt.value = value; 
    opt.text = text; 
    ddl.options.add(opt); 
    } 
</script> 

現在基於在第二個下拉列表中選擇的選項,我想運行一個mysql查詢並填充第三個下拉列表。有關如何填充第三個下拉列表的任何幫助。

+1

您需要在[AJAX](http://en.wikipedia.org/wiki/Ajax_(編程))中查找爲了從服務器請求額外的(和有條件的)數據 – juco 2013-03-06 10:39:09

回答

1

使用AJAX向您的服務器發送請求並運行mysql查詢。假設您沒有使用JQuery,純AJAX看起來像這樣:

if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
     xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      var data = xmlhttp.responseText; 
      //populating your select 
     } 
     } 
     xmlhttp.open("GET", "yourmethodpath", true); 
     xmlhttp.send(); 
    } 
+0

謝謝你的回答!我可以讓AJAX在服務器上執行一個php腳本嗎?也從來沒有使用AJAX之前,所以你可以指點我的一些資源,這將幫助我開始使用AJAX? – 2013-03-07 06:11:48

+0

我強烈推薦W3C Ajax教程。它的速成教程,如果你知道一些HTML/JavaScript http://www.w3schools.com/ajax/default.asp – Husman 2013-03-07 09:18:46

+0

謝謝!已經在它:) – 2013-03-10 03:10:23

1

使用Ajax,我做我的一個項目非常類似的東西,所以下面有一個例子:

$('#product_series_text', $('#product_form')).change(function() { 
    var $series = $(this).val(); 
    // Ajax request to get an updated list of product models 
    $.getJSON(
    "<?php echo url::site('product/get_model_like_series'); ?>", 
    { series: $series }, 
    function(data) { 
     $("#product_model", 
     $('#product_form')).form_utils('replaceOptions', data); 
    }); 
}); 

Theres很多的jQuery有,但這個想法是有一個事件偵聽在一個變化然後觸發一個Ajax查詢(查詢數據庫並返回一個Json的結果列表),然後爲我們創建一個下拉列表(只是因爲下拉列表已經存在而改變了選項)

+0

感謝您指出了這一點,但我從未使用過AJAX,所以你可以指點我幾個資源,這將幫助我開始使用它? – 2013-03-07 06:09:05

相關問題