【问题标题】:How to use getJSON with this code如何在这段代码中使用 getJSON
【发布时间】:2014-02-17 10:37:59
【问题描述】:

我刚刚得到这个使用 JSON 数据填充选项的链接选择框。 Fiddle。数据是硬编码的,但我想使用$.getJSON() 方法加载数据,但我无法正确获取代码。我认为Suggest.json文件被触发,但似乎是其他原因导致了问题。谁能告诉我如何解决这个问题?

我从this site 得到了下拉框

原代码:

<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>

这是我失败的尝试:

  <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>

建议.JSON:

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

【问题讨论】:

  • 你要从同一个域或其他域获取 JSON 吗?
  • 您是否在 javascript 控制台中遇到任何错误?
  • @Evgeniy 我从同一个域中获取文件。它似乎被触发了。请稍等。我正在设置两个示例,一个具有硬编码数据,一个使用 getJSON 方法。
  • @anurupr 我设置了两个示例。示例:original ||| getJSON Example 除了原始警告(硬编码)event.returnValue is deprecated. Please use the standard event.preventDefault() instead. 中的警告之外,我没有看到任何错误。除此之外,它工作正常。
  • 我测试了你的代码,除了 jQuery("#mySelectID").dynamicDropdown({"delimiter":"|"});试试 jQuery("#mySelectID").show();也看到了

标签: javascript jquery html json getjson


【解决方案1】:

问题是,只有在 getJSON 向您返回数据时,您才必须调用 $("#mySelectID").dynamicDropdown({"delimiter":"|"});

根据您的代码,只需交换插件调用:

$(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":"|"});

    });
});

顺便说一句,你的 json 有一个错误:最后一项(南美)有“代码”,并根据其他项目注释 CODE”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2011-10-29
    • 2023-04-10
    • 1970-01-01
    • 2013-02-09
    • 2012-07-06
    • 1970-01-01
    相关资源
    最近更新 更多