[英]How to load JSON data based on a dropdown input?
我是 web 開發的新手,目前正在試驗 HTML forms。 我正在使用 Chrome 測試如何根據使用 jQuery 從標簽中進行的選擇在 div 中顯示 JSON 數據,但我的代碼無法正常工作。 當我檢查我的網頁時,它顯示了要加載的 JSON 的 div,但是從下拉菜單中選擇一個元素后數據本身不存在。 另外,如果這有什么不同,我正在使用樣式表。 我做錯了嗎?
<json>
{
"firstName": "Jason",
"lastName": "Bourne"
},
{
"firstName": "John",
"lastName": "McClane"
}
<html>
<div id="names">
<select id ="drop-list">
<option value="" disabled="disabled" selected="selected">--Select A Name--</option>
<option>Jason Bourne</option>
<option>John McClane</option>
</select>
</div>
<javascript>
$(function() {
let names = $('#names');
dropList.on('select', getDataViaAjax);
function getDataViaAjax(evnt) {
let request = $.ajax({
method: 'GET',
url: 'people.json',
dataType: 'json',
});
request.done(function(data) {
console.log(data);
let dropList = $('#drop-list');
for (let person of data) {
let newParagraph = $('<p>');
newParagraph.text(person.firstName + ' last name ' + person.lastName);
dropList.append(newParagraph);
}
});
request.fail(function(response) {
console.log('ERROR:' + response.statusText);
});
}
});
我曾經使用過這種結構,我認為它簡單但有效,希望它可以工作:
//在你的 html
<form>
<select id="filterAgendas">
</select>
</form>
//在應用程序中,js
$.ajax({
url: 'YourJsonFileLocation',
type: 'GET',
success: function(response) {
console.log(response);
const list = JSON.parse(response);
let filter = '';
list.forEach(list => {
filter += `<option value="${list.id}"> ${list.name}</option>`
});
$('#filterAgendas').html(filter);
}
});
//你的 json 文件
{
{
id: 1,
name: name1
},
{
id: 2,
name: name2
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.