Ответ 1
На самом деле это довольно просто:
Если вы читаете HTML-код, вы заметите, что нажатие кнопки "Сделать мяч" вызовет addObject(). Итак, вы идете и проверяете эту функцию в JS-коде. addObject() просто анализирует значения из входных полей в объект, называемый spec, а затем вызывает makeBall (spec).
Что вам нужно сделать, так это предоставить ту же спецификацию объекта данных для функции makeBall для каждого из ваших данных JSON.
function addObjectsFromJson(json){
// using try catch block because JSON.parse will throw an error if the json is malformed
try{
var array = JSON.parse(json);
for(var i = 0; i < array.length; i++){
var planet = array[i];
// create a spec to use with makeBall from the json
var spec = {
element: {
id: planet.rowid,
// you don't provide a style class in your json yet, using yellow as default
class: 'st0',
// your json must have a standard property for radius,
// currently you have "Radius size" (is wrong since
// properties cannot have spaces) and "Size"
r: planet["Planet Radius [Jupiter radii]"]
},
animation: {
speed: 2,
spin: 30,
side: planet["Distance [pc]"]
}
};
makeBall(spec);
}
}catch(e){
console.log('error: ' + e);
}
}
Я не вижу свойства для добавления расстояния в функции makeBall().
Обрабатывать JSON через ajax с помощью jQuery:
// assuming your local server runs on port 8080
$.getJSON('localhost:8080/path/to/your/file', function (json) {
// since we use getJSON, it is already parsed and a javascript object
// additional parsing inside the addObjectsFromJson function is not necassary
// and would throw an error
addObjectsFromJson(json);
});
function addObjectsFromJson(json) {
for (var i = 0; i < json.length; i++) {
var planet = json[i];
// create a spec to use with makeBall from the json
var spec = {
element: {
id: planet.rowid,
// you don't provide a style class in your json yet, using yellow as default
class: 'st0',
// your json must have a standard property for radius,
// currently you have "Radius size" (is wrong since properties cannot have spaces) and "Size"
r: planet["Planet Radius [Jupiter radii]"]
},
animation: {
speed: 2,
spin: 30,
side: planet["Distance [pc]"]
};
makeBall(spec);
}
}