我有一个包含国家和地区信息的countries.json文件。我让用户通过Python生成的下拉列表从countries.json文件中选择国家。这将起作用,并选择国家/地区。但是因为python在后台工作,所以我不能调用第二个阶段"state“,除非用户首先提交表单。
因此,我可以使用以下命令调用在JavaScript中选择的国家/地区:
document.getElementById("country").addEventListener("change", function() {
let country_chosen = document.getElementById("country").value;
});这是可行的。因此,用户输入了国家/地区,根据更改,国家/地区的名称现在显示在控制台中。
JSON文件中的单个条目可能如下所示(这只是第一个条目):
{
"code2": "AF",
"code3": "AFG",
"name": "Afghanistan",
"capital": "Kabul",
"region": "Asia",
"subregion": "Southern Asia",
"states": [
{
"code": "BDS",
"name": "Badakhshān",
"subdivision": null
},对于这个例子,如果用户从Python生成的下拉列表中选择阿富汗,那么他们还可以根据阿富汗的所有州选择一个州,等等。
输入选择基于Jinja模板:
<select name="country" id="country" ref="country">
{% for country in countries %}
{% if profile.country == country.name %}
<option value="{{ country.name }}" selected>{{ country.name }}</option>
{% else %}
<option value="{{ country.name }}">{{ country.name }}</option>
{% endif %}
{% endfor %}
</select>所以,我想重复一个类似的输入,除了从前端由JS驱动。
因此,我将有一个select状态“name=”,这样Python就可以在提交时读取输入,但这一部分的其他所有内容都需要由JS驱动。因此,for循环将调用该国家/地区的所有州。
但不幸的是,这是我以前从未做过的事情。我从未使用JS调用过JSON文件,更不用说我自己生成(好吧,复制)并存储在站点上的JSON文件了。那么,我该从哪里开始呢?我有所选国家的名称,现在如何调用JSON文件来填充州输入下拉列表?
感谢你在这篇文章中帮助我找到了正确的方向。
我在jQuery中尝试这样做,但我什么也得不到,没有错误,什么都没有:
$.ajax({
url: 'countries.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data){
$.each(data['states'], function(index, value){
console.log(index);
console.log(value['name']);
console.log(country_chosen);
})
}
});发布于 2021-01-07 02:52:30
使用fetch,ES6:
fetch('my/url') // Call the fetch function passing the url of the API as a parameter
.then(function(data) {
// Your code for handling the data you get from the API
})
.catch(function() {
// This is where you run code if the server returns any errors
});使用XMLHttpRequest,Vanilla JS:
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();https://stackoverflow.com/questions/65598987
复制相似问题