<html>
<head>
</head>
<body>
<select id=
"people"
></select>
</body>
The JSON file we’ll be using consists of a collection of ‘person’ data in a valid JSON form, such as:
{
"person"
: [
{
"id"
:
"1"
,
"name"
:
"Person1"
},
{
"id"
:
"2"
,
"name"
:
"Person2"
},
{
"id"
:
"3"
,
"name"
:
"Person3"
}
]}
<script type=
"text/JavaScript"
>
//getJSON
var
$select = $(
'#people'
);
$.getJSON(
'person.JSON'
,
function
(data){
$select.html(
''
);
$.each(data.person,
function
(key, val){
$select.append(
'<option id="'
+ val.id +
'">'
+ val.name +
'</option>'
);
})
});
//AJAX
$select = $(
'#people'
);
$.ajax({
url:
'person.JSON'
,
dataType:
'JSON'
,
success:
function
(data){
$select.html(
''
);
$.each(data.person,
function
(key, val){
$select.append(
'<option id="'
+ val.id +
'">'
+ val.name +
'</option>'
);
})
},
error:
function
(){
$select.html(
'<option id="-1">none available</option>'
);
}
});
</script>
</html>
https://developerdan77.wordpress.com/2011/10/14/dynamically-populate-a-select-element-from-json-data-with-jquery/
No comments:
Post a Comment