2014-02-25 25 views
0

我試圖使用jQuery來填充以下JSON數據使用JSON數據下拉框

{ 
    "Name":["A","B","C"], 
    "Movie":["X","Y","Z"] 
    } 

的下拉框,這個劇本是我迄今所做

$("#firstbox").change(function(){ 
    var $selection=$(this); 

    $.getJSON("data.json",function(data){ 
    var i=$selection.val(); 
    var arr=[]; 

    switch(i){ 
     case 'Name': 
      arr=data.Name.split(","); 
      break; 
     case 'Movie': 
      arr=data.Movie.split(","); 
      break; 
    }  

    }); 

    }); 

我的基本index.html就像這樣

<select id="firstbox"> 
      <option selected value="">---Select---</option> 
      <option value="Name">Name</option> 
      <option value="Movie">Movie</option> 
    </select> 

    <select id="secondbox" name=""> 
      <option selected value="">---Generate---</option> 
      <script src="myjs.js"> </script> 
    </select> 

'secondbox'下拉菜單應該生成對應於'firstbox'下拉菜單的選擇。我收到的錯誤是'未定義分割功能'。任何人都可以給我一個提示嗎?

感謝

回答

1

splitString對象的方法,在這裏你使用它的Array對象。 您不需要拆分,因爲Name和Movie鍵是JSON對象中的allready數組。

$("#firstbox").on("change", function(e){ 
    var sel=$(this).val(); 
    $("#secondbox").empty(); 
    $.getJSON("data.json",function(data){ 
     var values=data[sel] || ['Error : key not found']; 
     $(values).each(function(index,element) { 
      $("<option />", {value: element, text:element}).appendTo("#secondbox"); 
     }); 
    }); 
}); 

這裏是一個工作爲例:http://jsfiddle.net/cKBeE/

+0

感謝了很多。它的作品完美! – user3063604

1
$("#firstbox").on("change", function(e){ 
writeOptions(); 
} 

function getJSONData(firstboxval) { 
    //make ajax call to get data for second dropdown 
    //that corresponds to the value selected in firstbox 
    //then make function return the array of options 
} 

function writeOptions() { 
    var firstboxval = $("#firstbox").val(); 
    var optionValues = getJSONData(firstboxval); 
    var dropDown = document.getElementById("secondbox"); 

    for(var i=0; i<optionValues.length; i++) { 
     var key = i; 
     var value = optionValues[i]; 
     dropDown.options[i] = new Option(value, key); 
    } 
} 
+0

謝謝,也給了我一個替代解決方案 – user3063604