jQuery函数读取JSON数据。用于填充选择

时间:2016-06-03 23:15:51

标签: jquery json

标题可能不是很清楚,但这是我需要做的。 我有这两个JSON文件:

?({
Makes:[
   {
    "make_id":"ac",
    "make_display":"AC",
    "make_is_common":"0",
    "make_country":"UK"
   },
   {
    "make_id":"acura",
    "make_display":"Acura",
    "make_is_common":"1",
    "make_country":"USA"
   },
  {etc...}
]});

?({
Models:[
   {
    "model_name":"Escape",
    "model_make_id":"ford"
   },
   {
    "model_name":"Excursion",
    "model_make_id":"ford"
   },
   {etc...}
]});

我想填充2个选项:

<select id= "dropDownDest">
</select>
<select id= "dropDownDest2">
</select>

具有以下功能:

 CreateSelectFromJson(jsonMakesUrl,"#dropDownDest","Makes","make_id","make_display");
CreateSelectFromJson(jsonModelsUrl,"#dropDownDest2","Models","model_name","model_name");

我做了类似的事情,但无法弄清楚如何传递最后3个参数。 此功能仅适用于我在函数内部编写参数的模型(它们是:data。模型,其中模型需要替换为 nodo 和val (值。 model_name )。text(值。 model_name )由 parameter1 parameter2 )。

function CreateSelectFromJson(jsonfromurl,idselect,nodo,parameter1,parameter2){
    appendSelectLoader(idselect,"Caricamento..."); //aggiunge un option con il caricamento
    $.getJSON(jsonfromurl,function(data)
   {
     $(idselect + " option").remove();
     $(idselect).prop( "disabled", false );
         $.each(data.Models,function(key,value)
         {
             var option = $('<option />').val(value.model_name).text(value.model_name);
        $(idselect).append(option);
         });

    });
}

function appendSelectLoader(idselect,testo) {
    $(idselect).prop( "disabled", true );
    var option = $('<option />').val("").text(testo);
     $(idselect).append(option);
}

1 个答案:

答案 0 :(得分:1)

您需要获取json文件的值,例如

function CreateSelectFromJson(jsonfromurl, idselect, nodo, parameter1, parameter2) {
  appendSelectLoader(idselect, "Caricamento..."); //aggiunge un option con il caricamento
  $.getJSON(jsonfromurl, function(data) {
    $(idselect + " option").remove();
    $(idselect).prop("disabled", false);
    $.each(data[nodo], function(key, value) {
      var option = $('<option />').val(value[parameter1]).text(value[parameter2]);
      $(idselect).append(option);
    });

  });
}

function appendSelectLoader(idselect, testo) {
  $(idselect).prop("disabled", true);
  var option = $('<option />').val("").text(testo);
  $(idselect).append(option);
}

$(document).ready(function() {

  CreateSelectFromJson('Makes.json', "#dropDownDest", "Makes", "make_id", "make_display");
  CreateSelectFromJson('Models.json', "#dropDownDest2", "Models", "model_name", "model_name");

});

See the Plunker