I’m trying to populate a form (onClick) with data from a JSON file.
I can do it succcesfully from an array but when I try to parse the local (same folder as the .html) JSON file it doesn’t work.
<script>
var marks = [];
$(document).ready(function() {
$("#RQdata").click(function(event) {
$.getJSON('test.json', function(data) {
$.each(data.markers, function(key, val) {
marks.push(val[key]);
});
});
});
});
function populateList() {
for (var i = 0; i < marks.length; i++) {
var mark = new Option(marks[i].name, markers[i].latlng);
document.getElementById('locationList').options.add(mark);
}
}
</script>
<h2>List</h2>
<form name="aForm">
<select name="locationList" id="locationList" size="6" onChange="alert(value);" style=" width:800px;owerflow: auto;">
</select>
<input type="button" id="RQdata" name="Request Data" value="Request Data" >
</form>
my test.json
{"markers":
[{"latlng":[55.587,17.044],"name":"Some name 1"},
{"latlng":[55.577,17.044],"name":"Some name 2"},
{"latlng":[55.507456,17.617585],"name":"Some name 3"},
{"latlng":[55.25642,17.154904],"name":"Some name 4"},
{"latlng":[55.103217,17.07776],"name":"Some name 5"}]}
Best regards
There’re several mistakes in your code, and the version below works.
Please use inspector or something else to debug.
Also, as @matt mentioned in the comment, some browser (like Chrome) will prohibit access to local file by XHR.