How to get the value of n-th item in a JSON list (using JQuery)?
How do I retrieve the n-th value in a JSON file (and maybe it's children, too)?
For example, I have a collection of courses and associated events formatted in JSON, which I'm using to populate a couple of select lists, e.g:
// extract from courselist.php
[{
"optionValue": "Getting Research into Practice",
"events": [
{"date": "29 October"}
]
},
{
"optionValue": "Human Resources for Managers",
"events": [
{"date": "September 1"},
{"date": "November 2"}
]
}]
I'm doing this to create the form from that JSON:
$(function(){
$("select#coursetype").change(function(){
开发者_开发技巧 $.getJSON("courselist.php",{id: $(this).val(), ajax: 'true'}, function(data){
var options = ''; //item in select list
options += '<option value=""></option>';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + [i] + '">' + data[i].optionValue + '</option>';
$("#courselist").html(options);
$('#courselist option:first').attr('selected', 'selected');
};
})
})
});
..which outputs HTML along the lines of:
<select id="coursetype" name="coursetype">
<option value="0">Getting Research into Practice</option>
<option value="1">Human Resources for Managers</option>
</select>
Say, the user selects 'Human Resources for Managers' (value="1"), and $_POSTs the form, how can I later retrieve that course name and it's event info from the POST value?
Provided you still have the JSON object available, you can just feed the posted value back into it as an index:
var courseName = data[postValue].optionValue;
var courseEvents = data[postValue].events;
for(theDate in courseEvents){
// do something with the date
}
精彩评论