您可以使用jquery或javaScript读取此JSON

As you can read this JSON using jquery or javaScript

本文关键字:读取 JSON javaScript 可以使 jquery      更新时间:2023-09-26

您可以使用jQuery或JavaScript读取此JSON。我从不使用JSON。

{
    "ES": {
        "130": {
            "code": "A Coruсa",
            "name": "A Coruña"
        },
        "131": {
            "code": "Alava",
            "name": "Alava"
        },
        "132": {
            "code": "Albacete",
            "name": "Albacete"
        }

To a select:

<select id="provincias">
    <option value="130">A Coruña</option>
    <option value="131">Alava</option>
    <option value="132">Albacete</option>
</select>

您可以使用 jQuery.map()

var data = {
  "ES": {
    "130": {
      "code": "A Coruсa",
      "name": "A Coruña"
    },
    "131": {
      "code": "Alava",
      "name": "Alava"
    },
    "132": {
      "code": "Albacete",
      "name": "Albacete"
    }
  }
};
// generate dropddown 
$('<select/>', {
  // setting id attribute
  id: 'provincias',
  // setting html content, iterating over JSON to add options
  html: $.map(data.ES,function(v,i) {
    // creating otions
    return $('<option/>', {
      // setting value as index in json
      value: i,
      // setting text content 
      text: v.name
    })
  })
  //appending the generated dropdown to the body
}).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

你可以使用递归:

var data = {
  "ES": {
    "130": {
      "code": "A Coruсa",
      "name": "A Coruña"
    },
    "131": {
      "code": "Alava",
      "name": "Alava"
    },
    "132": {
      "code": "Albacete",
      "name": "Albacete"
    }
  }
};
function setOptions(data) { // get data in the args
  var option = ''; // create a var to hold the options to be created.
  for (key in data) { // use for in loop to get the key and values
    if (data[key].constructor === Object) { // check if data is an object
      option += '<option value="' + key + '">' + data[key].name + '</option>'; // create option
      setOptions(data[key]); // pass the object again in the same function to get the "name" value.
    }
  }
  document.getElementById('provincias').innerHTML = option; // finally push in the dom.
}
setOptions(data.ES); // pass the data here, we're targeting ES5
<select id="provincias">
</select>