Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - Populate drop down menu from file html

Have been trying to do a simple drop down menu populated from a file where I would have an id and a list of names associated with that id:

ex:

id, names
1, ['John', 'Maria', 'Mario']
2, ['Fabio', 'Gary', 'Yanni', 'Charlie']

For the first drop down - John, Maria and Mario will be displayed. When clicking 'Next' Fabio, Gary, Yanni and Charlie will be shown. Is there an easy way how to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm gonna use php for this demo.

First it's better to use JSON format when sending and receiving data, but of course if you want to do it in any other way feel free to do so.

Javascript call to get for that data, i'll be using fetch() to make the ajax call if you don't quite understand what is it or what's ajax at all, i suggest you Check this

Let me know if you have any questions.

people.json :

{
    "1":["John", "Maria", "Mario"],
    "2":["Fabio", "Gary", "Yanni", "Charlie"]
}

Javascript :

// making ajax call to data.php which we will look at later
fetch('people.php')
// get data as json
    .then(rawdata => rawdata.json()) 
// here i'm just logging it, but you can do whatever you like with it.
    .then(data => console.log(JSON.parse(data)));

people.php :

// reading file `people.json` content like you would read any file in php
$data = file_get_contents('people.json');
// parsing it to json (array basically) 
$manage = json_decode($data);
// printing the array to the document 
// which is basically the response to the ajax call
print_r($data);

EDIT :

Or if you don't have any work to do on the data in the back end, you can just request the file directly from the Javascript

fetch('data.json')
    .then(rawdata => rawdata.json()) 
    .then(data => console.log(JSON.parse(data)));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...