在JQuery中用JSON填充SELECT

Populate a SELECT with JSON in JQuery

本文关键字:填充 SELECT JSON 中用 JQuery      更新时间:2023-09-26

我想在我的代码中得到一些帮助:

当我尝试使用变量而不是数组的键名时,返回值为NULL,有人可以告诉我如何使用变量而非固定名称。

谢谢。

var json = '[{"id":"8","top_cadastro_clientes_name":"USS SOLUCOES GERENCIADAS LTDA"},{"id":"9","top_cadastro_clientes_name":"AXA - INTER PARTNER ASSIST"},{"id":"10","top_cadastro_clientes_name":"BRASIL ASSISTENCIA SA"},{"id":"11","top_cadastro_clientes_name":"EUROP ASSISTANCE"},{"id":"12","top_cadastro_clientes_name":"MONDIAL SERVICOS LTDA"},{"id":"13","top_cadastro_clientes_name":"PARTICULAR ATIVO"}]';
  
var select = $('select');
var referencedcolumn = 'id';
var referencedfield  = 'top_cadastro_clientes_name';
var opts = $.parseJSON(json);
  $.each( opts, function(key, val) {
    select.append('<option value="'+val.id+'">'+val.id+'-'+val.referencedfield+'</option>');
  
    console.log('why print NULL when i use variable for field???'+val.referencedcolumn);
  });
<select class="form-control" name="select" data-referencedtable="" data-referencedcolumn="" data-referencedfield="">
  <option value="0" selected="selected">Selecione...</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

您正在寻找数组语法:

$.each( opts, function(key, val) {
  select.append('<option value="'+val[referencedcolumn]+'">'+val[referencedcolumn]+'-'+val[referencedfield]+'</option>');
  console.log('print id column value: '+val[referencedcolumn]);
});