问题
I'm doing a webpage that contains a JQuery UI slider, where you can select a year. After the stop event of the slider, I want the webpage to show the data from a JSon file related to the year I have chosen. First, I would like to know if doing this dinamically is possible (I'm using HTML + CSS + JavaScript).
And second, here is the stop event of the slider:
stop: function (event, ui) {
alert('Stopped at ' + ui.value);
$.getJSON('winners.json', function(winners) {
var output=" ";
output+=winners.driver[ui.value].name;
document.getElementById("winner").innerHTML=output;
});
}
The alert shows properly the year selected in the slider.
winners.json has 2 fields (year, name), driver is the name of the JSon Array and winner is a placeholder in the HTML
回答1:
From your description of winners.json, it sounds like you have an object named driver that contains an array. Each object in the array has two fields: year and name. Then, you are trying to access the name field as if it was nested within the year field...instead of being a sibling of the year field. If this is the case, you either need to restructure your winners.json file to match your code, or easier...change your code to access the name correctly.
If they are siblings, you could do something like this:
for (var i=0,len=winners.driver.length; i < len; i++) {
if(winners.driver[i].year === ui.value){
output += winners.driver[i].name;
}
}
Also, make sure that the winners.json file is uploaded to your web server, and you are specifying the correct path when you make your call. Based on what you have, it would be looking in the same directory as your HTML file that's making the call.
来源:https://stackoverflow.com/questions/17252443/obtain-data-from-json-after-choosing-a-field-with-a-jquery-ui-slider