在一门课上,我被要求使用 HTML5 和 JavaScript 在表单中制作一个动态下拉菜单。我做到了here .
现在,我需要从 JSON 文件中调用数据。我查看了 SOF 上的其他答案,但仍然不太了解如何使用 JQuery 从 JSON 文件中获取信息。
我需要有 2 个字段:第一个字段是国家/地区。 JSON 键是 country
值为 state
.可以找到 JSON 文件和内容的副本 here .第二个下拉字段仅添加与其相关国家/地区相关的值/数组。
这是我的 HTML5 文件的副本:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
这是我到目前为止编写的 JS 文件的副本,它试图从 JSON 文件中获取数据但失败了:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
这里是另一个添加字段指令的JS文件的内容:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
这应该至少将值添加到字段中,但网页上只出现空框。
然后我需要像 here 中那样做一个条件语句但调用或引用来自 JSON 文件的数据。
我只学过一些 HTML 和 JavaScript 的类(class),没有学过 JQuery 和 JSON。因此,您的帮助将大大增加我的知识,对此我将不胜感激。
谢谢!!
我找到了这个 SOF answer并将我的 JS 文件更改为以下内容:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
并且,我按如下方式编辑了我的 HTML 文档:
<form id="locationSelector" enctype='application/json'></form>
我删除并重新添加了 <select>
标签和以下至少我得到一个空白框:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
我觉得我越来越近了,但还是迷路了。
最佳答案
你能试试这个吗:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});
关于javascript - 创建一个使用 JQuery 从 JSON 文件加载数据的动态下拉表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39888014/