简体   繁体   English

从JSON文件填充表单

[英]populating a form from JSON file

I'm trying to populate a form (onClick) with data from a JSON file. 我正在尝试使用JSON文件中的数据填充表单(onClick)。 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. 我可以从数组成功完成此操作,但是当我尝试解析本地(与.html相同的文件夹)JSON文件时,它不起作用。

<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 我的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. 您的代码中有几个错误,下面的版本适用。

var marks = [];
$(document).ready(function() {
$("#RQdata").click(function(event) {
    $.getJSON('test.json', function(data) {
    $.each(data.markers, function(key, val) {
        marks.push(val);  //It should be val instead of val[key]
    });

    populateList();  // You didn't call this function here
    });
});
});

function populateList() {
for (var i = 0; i < marks.length; i++) {
    var mark = new Option(marks[i].name, marks[i].latlng);  //marks instead of markers here
    document.getElementById('locationList').options.add(mark);
}
}

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. 另外,正如评论中提到的@matt一样,某些浏览器(例如Chrome)将禁止XHR访问本地文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM