使用模板

时间:2015-08-13 23:10:55

标签: javascript jquery html laravel jquery-select2

尝试研究如何将select2模板函数与动态select2下拉列表一起使用,以便在JSON响应中显示额外数据

我的问题与如何创建HTML模板格式无关(我已经想到了)。我想知道如何在加载远程数据时进行模板工作 - 此时远程数据加载功能会覆盖模板...

下面是我的意思的一个例子"模板"结果。我希望能够具体化" otherData"和" extraData"字段

Example of templating

当前示例数据格式(由以下代码使用,不能用于模板化)

  

{" 12":" DASGDSA67"}

建议的示例数据(作为带有额外数据的JSON)

  

{" ID":" 12""值":" DASGDSA67"" otherData":& #34;不伦瑞克""&而额外#34;:"头及#34;}

查看(Javascript)

<script type="text/javascript">
$(document).ready(function() {
    $(".company2").select2();
    $(".location2").select2({
        templateResult: formatState
    });
});

$(".company2").select2().on('change', function() {
var $company2 = $('.company2');
$.ajax({
    url:"../api/locations/" + $company2.val(),
    type:'GET',
    success:function(data) {
        var $location2 = $(".location2");
        $location2.empty();
        $.each(data, function(value, key) {
            $location2.append($("<option></option>").attr("value", value).text(key));
        }); 
        $location2.select2();
    }
});
}).trigger('change');

function formatState (state) {
  if (!state.id) { return state.text; }
      var $state = $(
         '<h1>' + state.element.value() + '</h1>' + '<p>' + state.element.otherData() + '</p>'
      );
  return $state;
};
</script>

0 个答案:

没有答案
相关问题