简体   繁体   中英

How to use getJSON with this code

I just got this chained select box working that uses JSON data to populate the options. Fiddle . The data is hard-coded, but I want to load the data using the $.getJSON() method, but I can't get the code right. I think the suggest.json file is triggered, but something else seems to be causing the problem. Would anyone please show me how to fix the problem?

I got the The Drop down Box from this site

The original code:

<script type="text/javascript">

var s = '[{"Box1":"Africa","CODE":1,"ID":"A"},{"Box1":"Asia","CODE":2,"ID":"B"},{"Box1":"South America","Code":3,"ID":"C"}]';


var jsonData = $.parseJSON(s);

var $select = $('#mySelectID');
$(jsonData).each(function (index, o) {    
    var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
    $select.append($option);
});

jQuery("#mySelectID").dynamicDropdown({"delimiter":"|"});

</script>

Here's my failed attempt:

  <script type="text/javascript">

  $.getJSON('suggest.json', function(data){

  var $select = $('#mySelectID');

  $.each(data, function (index, o) {

  var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
    $select.append($option);
  });

  });
  jQuery("#mySelectID").dynamicDropdown({"delimiter":"|"});
  </script>

Suggest.JSON:

[{"Box1":"Africa","CODE":1,"ID":"A"},{"Box1":"Asia","CODE":2,"ID":"B"},{"Box1":"South America","Code":3,"ID":"C"}]

The problem is that you haved to call $("#mySelectID").dynamicDropdown({"delimiter":"|"}); only when getJSON return you the data.

According to your code, just swap the plugin call :

$(document).ready(function(){
    $.getJSON('my.json', function(data){

        var $select = $('#mySelectID');

        $.each(data, function (index, o) {
            var $option = $("<option/>").attr("value", o.CODE).text(o.Box1 + "|" + o.ID);
            $select.append($option);
        });

        $("#mySelectID").dynamicDropdown({"delimiter":"|"});

    });
});

By the way, you have an error with your json : the last item (South America) have "Code" and note CODE" according to the others

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM